"""Bounded admission; request cancellation does not undo a committed operation."""
from __future__ import annotations

import asyncio
from dataclasses import dataclass
import hashlib
import json
import logging
from opentelemetry.context import Context, get_current
from opentelemetry.trace import Status, StatusCode, Tracer

from .contracts import ConflictError, ImportInput, ImportResult, Store


class CapacityError(Exception):
    pass


@dataclass
class Job:
    owner: str
    key: str
    payload: ImportInput
    result: asyncio.Future[ImportResult]
    request_id: str
    trace_context: Context


class ImportQueue:
    def __init__(self, store: Store, capacity: int = 4, tracer: Tracer | None = None) -> None:
        self.store = store
        self.tracer = tracer
        self.queue: asyncio.Queue[Job | None] = asyncio.Queue(maxsize=capacity)
        self.accepting = False
        self.task: asyncio.Task[None] | None = None
        self.completed = 0
        self.failed = 0
        self.close_task: asyncio.Task[None] | None = None

    async def start(self) -> None:
        if self.task is not None:
            raise RuntimeError("queue lifecycle cannot be started twice")
        self.task = asyncio.create_task(self.run(), name="import-worker")
        self.accepting = True

    def submit(self, owner: str, key: str, payload: ImportInput,
               request_id: str = "-") -> asyncio.Future[ImportResult]:
        if not self.accepting:
            raise CapacityError("service is draining")
        result: asyncio.Future[ImportResult] = asyncio.get_running_loop().create_future()
        # Retrieve background failures even when the HTTP waiter has gone away.
        result.add_done_callback(lambda future: None if future.cancelled() else future.exception())
        try:
            self.queue.put_nowait(Job(owner, key, payload, result, request_id, get_current()))
        except asyncio.QueueFull as exc:
            raise CapacityError("import queue is full") from exc
        return result

    async def run(self) -> None:
        while True:
            job = await self.queue.get()
            try:
                if job is None:
                    return
                try:
                    work = asyncio.create_task(asyncio.to_thread(self.execute, job))
                    try:
                        outcome = await asyncio.shield(work)
                    except asyncio.CancelledError:
                        # Cancelling the consumer does not kill its DB thread. Reap work first.
                        try:
                            await work
                        finally:
                            if not job.result.done():
                                job.result.set_exception(RuntimeError("consumer cancelled"))
                        raise
                except Exception as exc:
                    self.failed += 1
                    logging.getLogger("log_capstone.jobs").error(json.dumps({
                        "event": "import.failed", "request_id": job.request_id,
                        "key_hash": hashlib.sha256(job.key.encode()).hexdigest()[:16],
                        "exception_type": type(exc).__name__}))
                    if not job.result.done():
                        job.result.set_exception(exc)
                else:
                    self.completed += 1
                    # A cancelled waiter must not kill the shared consumer.
                    if not job.result.done():
                        job.result.set_result(outcome)
            finally:
                self.queue.task_done()

    def execute(self, job: Job) -> ImportResult:
        if self.tracer is None:
            return self.store.ingest(job.owner, job.key, job.payload)
        # A queued task needs explicit context; worker creation preceded the request.
        with self.tracer.start_as_current_span("import.transaction", context=job.trace_context,
                record_exception=False, set_status_on_exception=False) as span:
            try:
                return self.store.ingest(job.owner, job.key, job.payload)
            except ConflictError:
                span.set_attribute("operation.outcome", "conflict")
                raise
            except Exception:
                # DB exception messages may contain SQL parameters; export only safe status.
                span.set_status(Status(StatusCode.ERROR))
                raise

    async def close(self) -> None:
        self.accepting = False
        if self.close_task is None:
            self.close_task = asyncio.create_task(self.drain())
        await asyncio.shield(self.close_task)

    async def drain(self) -> None:
        joined = asyncio.create_task(self.queue.join())
        try:
            if self.task is None:
                return
            done, _ = await asyncio.wait({joined, self.task}, return_when=asyncio.FIRST_COMPLETED)
            if self.task in done:
                outcome = (await asyncio.gather(self.task, return_exceptions=True))[0]
                if isinstance(outcome, BaseException):
                    raise RuntimeError("consumer stopped before drain completed") from outcome
                raise RuntimeError("consumer stopped before drain completed")
            await self.queue.put(None)
            await self.task
        finally:
            joined.cancel()
            await asyncio.gather(joined, return_exceptions=True)
            while not self.queue.empty():
                pending = self.queue.get_nowait()
                if pending is not None and not pending.result.done():
                    pending.result.set_exception(RuntimeError("consumer unavailable"))
                self.queue.task_done()
            self.store.close()
        # No forced cancellation of a running DB thread is claimed here.
        # External process supervision must still define a hard stop budget.
