from __future__ import annotations

import asyncio
import fcntl
import hmac
import os
from contextlib import asynccontextmanager
from typing import Optional
from uuid import UUID

from fastapi import Depends, FastAPI, Header, HTTPException, Response, status
from fastapi.responses import JSONResponse

from .adapters import PodmanAdapter, SimulatedAdapter, SyncAdapter
from .config import Settings
from .runner import WorkerRunner
from .schemas import CreateRun, RunSnapshot
from .storage import ActiveRunConflict, IdempotencyConflict, Store

class RequestSizeLimit:
    def __init__(self, app, limit: int):
        self.app, self.limit = app, limit

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return
        content_length = next((value for key, value in scope.get("headers", []) if key.lower() == b"content-length"), None)
        if content_length:
            try:
                if int(content_length) > self.limit:
                    response = JSONResponse({"detail": "Request body too large"}, status_code=413)
                    await response(scope, receive, send)
                    return
            except ValueError:
                response = JSONResponse({"detail": "Invalid Content-Length"}, status_code=400)
                await response(scope, receive, send)
                return
        chunks = []
        size = 0
        more = True
        while more:
            message = await receive()
            if message["type"] == "http.disconnect":
                return
            chunk = message.get("body", b"")
            size += len(chunk)
            if size > self.limit:
                response = JSONResponse({"detail": "Request body too large"}, status_code=413)
                await response(scope, receive, send)
                return
            chunks.append(message)
            more = message.get("more_body", False)
        index = 0

        async def replay():
            nonlocal index
            if index < len(chunks):
                message = chunks[index]
                index += 1
                return message
            return {"type": "http.request", "body": b"", "more_body": False}

        await self.app(scope, replay, send)


def create_app(settings: Optional[Settings] = None, adapter: Optional[SyncAdapter] = None,
               store: Optional[Store] = None) -> FastAPI:
    settings = settings or Settings.from_env()
    if not settings.token or len(settings.token) < 24:
        raise ValueError("WORKER_TOKEN must contain at least 24 characters")
    store = store or Store(settings.database_path)
    adapter = adapter or (PodmanAdapter(settings) if settings.adapter == "podman" else SimulatedAdapter(settings.simulated_delay_seconds))
    runner = WorkerRunner(store, adapter, settings)

    @asynccontextmanager
    async def lifespan(app: FastAPI):
        instance_lock_path = settings.database_path.with_suffix(settings.database_path.suffix + ".instance.lock")
        instance_lock_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
        instance_lock = instance_lock_path.open("a+")
        os.chmod(instance_lock_path, 0o600)
        try:
            fcntl.flock(instance_lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError as exc:
            instance_lock.close()
            raise RuntimeError("Only one worker process may use this SQLite database") from exc
        task = None
        try:
            store.initialize()
            store.mark_existing_runs_uncertain()
            task = asyncio.create_task(runner.serve(), name="sync-worker-runner")
            app.state.worker_task = task
            yield
        finally:
            if task is not None:
                task.cancel()
                try:
                    await task
                except asyncio.CancelledError:
                    pass
            fcntl.flock(instance_lock.fileno(), fcntl.LOCK_UN)
            instance_lock.close()

    app = FastAPI(title="BI Sync Worker", version="1.0.0", docs_url=None, redoc_url=None,
                  openapi_url=None, lifespan=lifespan)
    app.state.store = store
    app.state.settings = settings
    app.add_middleware(RequestSizeLimit, limit=settings.max_request_bytes)

    async def authorize(authorization: Optional[str] = Header(default=None)) -> None:
        expected = "Bearer " + settings.token
        if authorization is None or not hmac.compare_digest(authorization.encode("utf-8"), expected.encode("utf-8")):
            raise HTTPException(status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": "Bearer"})

    @app.post("/api/v1/sync-runs", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(authorize)])
    async def create_run(payload: CreateRun, response: Response):
        try:
            snapshot, created = store.create(payload)
        except IdempotencyConflict:
            raise HTTPException(status_code=409, detail="run_id already exists with different request parameters")
        except ActiveRunConflict:
            raise HTTPException(status_code=409, detail="another run for this connection is active or requires reconciliation")
        if created:
            response.status_code = status.HTTP_202_ACCEPTED
            return {"run_id": str(payload.run_id), "status": "queued"}
        response.status_code = status.HTTP_200_OK
        return snapshot

    @app.get("/api/v1/sync-runs/{run_id}", response_model=RunSnapshot, dependencies=[Depends(authorize)])
    async def get_run(run_id: UUID):
        snapshot = store.snapshot(str(run_id))
        if snapshot is None:
            raise HTTPException(status_code=404, detail="Run not found")
        return snapshot

    return app


app = create_app()
