"""Factory-based API: configuration and resources are created during startup."""
import asyncio
from contextlib import asynccontextmanager
from dataclasses import dataclass
import hmac
import json
import logging
import os
from pathlib import Path
import re
import time
from typing import Annotated, AsyncIterator
import uuid

from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from starlette.responses import JSONResponse, Response
from starlette.middleware.base import RequestResponseEndpoint

from .contracts import ConflictError, ImportInput, ImportResult, Store, validate_operation_key
from .queueing import CapacityError, ImportQueue
from .storage import SqlStore
from .telemetry import Telemetry
from opentelemetry.trace import Status, StatusCode

logger = logging.getLogger("log_capstone.requests")


@dataclass(frozen=True)
class Principal:
    owner: str
    admin: bool = False


@dataclass(frozen=True)
class Settings:
    database: Path
    tokens: dict[str, Principal]
    queue_capacity: int = 4
    response_timeout: float = 1.0


class BodyLimit:
    """Check bytes before JSON parsing; bound chunked bodies as well as Content-Length."""
    def __init__(self, app: ASGIApp, max_bytes: int = 65536, read_timeout: float = 2.0) -> None:
        self.app, self.max_bytes, self.read_timeout = app, max_bytes, read_timeout

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return
        body = bytearray()
        deadline = time.monotonic() + self.read_timeout
        while True:
            try:
                message = await asyncio.wait_for(receive(), max(0, deadline-time.monotonic()))
            except TimeoutError:
                await JSONResponse({"detail": "request body read deadline expired"}, status_code=408)(scope, receive, send)
                return
            if message["type"] == "http.disconnect":
                return
            chunk = message.get("body", b"")
            if len(body) + len(chunk) > self.max_bytes:
                await JSONResponse({"detail": "request body exceeds limit"}, status_code=413)(scope, receive, send)
                return
            body.extend(chunk)
            if not message.get("more_body", False):
                break
        replayed = False

        async def replay() -> Message:
            nonlocal replayed
            if not replayed:
                replayed = True
                return {"type": "http.request", "body": bytes(body), "more_body": False}
            return await receive()

        await self.app(scope, replay, send)


def create_app(settings: Settings, store: Store | None = None,
               telemetry: Telemetry | None = None) -> FastAPI:
    if settings.queue_capacity < 1 or settings.response_timeout <= 0:
        raise ValueError("capacity and response timeout must be positive")
    reads: set[asyncio.Task[list[dict[str, object]]]] = set()
    observation = telemetry or Telemetry()

    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        if not settings.tokens or any(len(token) < 16 for token in settings.tokens):
            raise RuntimeError("configure API tokens of at least 16 characters")
        queue = ImportQueue(store or SqlStore(settings.database), settings.queue_capacity, observation.tracer)
        app.state.imports = queue
        app.state.requests = 0
        await queue.start()
        try:
            yield
        finally:
            queue.accepting = False
            # HTTP cancellation does not end a synchronous DB query in a thread.
            if reads:
                await asyncio.gather(*reads, return_exceptions=True)
            await queue.close()
            observation.close()

    app = FastAPI(lifespan=lifespan, title="Log import teaching service")
    app.add_middleware(BodyLimit)

    async def authenticate(authorization: Annotated[str | None, Header()] = None) -> Principal:
        supplied = authorization[7:] if authorization and authorization.startswith("Bearer ") else ""
        for token, principal in settings.tokens.items():
            if hmac.compare_digest(token.encode(), supplied.encode()):
                return principal
        raise HTTPException(401, "invalid credentials")

    @app.middleware("http")
    async def observations(request: Request, call_next: RequestResponseEndpoint) -> Response:
        candidate = request.headers.get("X-Request-ID", "")
        request_id = candidate if re.fullmatch(r"[A-Za-z0-9_-]{1,64}", candidate) else uuid.uuid4().hex
        request.state.request_id = request_id
        started = time.perf_counter()
        with observation.tracer.start_as_current_span("http.request") as span:
            try:
                response = await call_next(request)
            except Exception as exc:
                logger.error(json.dumps({"event": "request.failed", "request_id": request_id,
                                         "exception_type": type(exc).__name__}))
                response = JSONResponse({"detail": "internal error"}, status_code=500)
            route = getattr(request.scope.get("route"), "path", "unmatched")
            span.update_name(request.method + " " + route)
            span.set_attribute("http.route", route)
            span.set_attribute("http.response.status_code", response.status_code)
            if response.status_code >= 500:
                span.set_status(Status(StatusCode.ERROR))
            trace_id = format(span.get_span_context().trace_id, "032x")
        response.headers["X-Request-ID"] = request_id
        app.state.requests += 1
        # Route templates have bounded cardinality. Tokens and input bodies are never logged.
        route = getattr(request.scope.get("route"), "path", "unmatched")
        elapsed = time.perf_counter()-started
        observation.requests.add(1, {"route": route, "status": response.status_code})
        observation.duration.record(elapsed, {"route": route})
        logger.info(json.dumps({"request_id": request_id, "trace_id": trace_id, "route": route,
            "status": response.status_code, "elapsed_ms": round((time.perf_counter()-started)*1000, 3)}))
        return response

    @app.get("/health")
    async def health() -> dict[str, bool]:
        if not app.state.imports.accepting:
            raise HTTPException(503, "draining")
        return {"ready": True}

    @app.post("/imports", response_model=ImportResult)
    async def ingest(payload: ImportInput,
                     request: Request,
                     principal: Annotated[Principal, Depends(authenticate)],
                     idempotency_key: Annotated[str, Header(min_length=1, max_length=64)]) -> ImportResult:
        try:
            validate_operation_key(idempotency_key)
        except ValueError as exc:
            raise HTTPException(422, "invalid operation key") from exc
        try:
            queue: ImportQueue = app.state.imports
            future = queue.submit(principal.owner, idempotency_key, payload, request.state.request_id)
            # Waiting expires; the admitted operation may commit. Retry with the same key.
            return await asyncio.wait_for(asyncio.shield(future), settings.response_timeout)
        except CapacityError as exc:
            raise HTTPException(503, str(exc), headers={"Retry-After": "1"}) from exc
        except ConflictError as exc:
            raise HTTPException(409, str(exc)) from exc
        except TimeoutError as exc:
            raise HTTPException(504, "response wait expired; retry with the same operation key") from exc
        except Exception as exc:
            logger.error("import failed: %s", type(exc).__name__)
            raise HTTPException(503, "storage unavailable; retry with the same operation key") from exc

    @app.get("/records")
    async def records(principal: Annotated[Principal, Depends(authenticate)],
                      after: Annotated[int, Query(ge=0)] = 0,
                      limit: Annotated[int, Query(ge=1, le=100)] = 20) -> list[dict[str, object]]:
        queue: ImportQueue = app.state.imports
        if not queue.accepting:
            raise HTTPException(503, "draining")
        def read_owned() -> list[dict[str, object]]:
            with observation.tracer.start_as_current_span("records.query",
                    record_exception=False, set_status_on_exception=False) as span:
                try:
                    return queue.store.records(principal.owner, after, limit)
                except Exception:
                    span.set_status(Status(StatusCode.ERROR))
                    raise
        work = asyncio.create_task(asyncio.to_thread(read_owned))
        reads.add(work)
        def finish(task: asyncio.Task[list[dict[str, object]]]) -> None:
            reads.discard(task)
            if not task.cancelled():
                task.exception()
        work.add_done_callback(finish)
        try:
            return await asyncio.shield(work)
        except Exception as exc:
            raise HTTPException(503, "storage unavailable") from exc

    @app.get("/metrics")
    async def metrics(principal: Annotated[Principal, Depends(authenticate)]) -> dict[str, int]:
        if not principal.admin:
            raise HTTPException(403, "admin permission required")
        queue: ImportQueue = app.state.imports
        return {"requests": app.state.requests, "queued": queue.queue.qsize(),
                "completed": queue.completed, "failed": queue.failed}

    return app


def app_factory() -> FastAPI:
    # Explicit factory: importing this module does not read environment or open a database.
    token = os.environ.get("LOG_API_TOKEN", "")
    if len(token) < 16:
        raise RuntimeError("LOG_API_TOKEN must contain at least 16 characters")
    principals = {token: Principal("operator", admin=True)}
    viewer = os.environ.get("LOG_VIEWER_TOKEN", "")
    if viewer:
        if len(viewer) < 16 or viewer == token:
            raise RuntimeError("LOG_VIEWER_TOKEN must be a distinct token of at least 16 characters")
        principals[viewer] = Principal("viewer", admin=False)
    return create_app(Settings(Path(os.environ.get("LOG_DATABASE", "logs.sqlite")), principals))
