"""
Cloud Run service wrapper for the FullEnrich webhook worker.

Runs an always-on queue consumer while exposing lightweight health endpoints
required by Cloud Run service health checks.
"""

from __future__ import annotations

import asyncio
import logging
import os
from contextlib import asynccontextmanager
from typing import Any, Dict

from fastapi import FastAPI
from fastapi.responses import JSONResponse

from fmatch.saas import settings
from fmatch.saas.workers.fullenrich_webhook_worker import (
    FULLENRICH_QUEUE,
    FullEnrichWebhookWorker,
)

logger = logging.getLogger(__name__)


def _resolve_worker_concurrency() -> int:
    override = os.getenv("FULLENRICH_WEBHOOK_WORKER_CONCURRENCY")
    if override:
        try:
            return max(int(override), 1)
        except ValueError:
            logger.warning(
                "Invalid FULLENRICH_WEBHOOK_WORKER_CONCURRENCY=%r; using WEBHOOK_WORKER_CONCURRENCY.",
                override,
            )
    return max(int(settings.WEBHOOK_WORKER_CONCURRENCY or 5), 1)


@asynccontextmanager
async def lifespan(app: FastAPI):
    worker = FullEnrichWebhookWorker(
        concurrency=_resolve_worker_concurrency(),
        manage_signals=False,
    )
    worker_task = asyncio.create_task(worker.start(), name="fullenrich-webhook-worker")
    app.state.worker = worker
    app.state.worker_task = worker_task
    logger.info(
        "Started FullEnrich webhook worker service (queue=%s, concurrency=%d).",
        FULLENRICH_QUEUE,
        worker.concurrency,
    )
    try:
        yield
    finally:
        worker.stop()
        try:
            await asyncio.wait_for(worker_task, timeout=30)
        except asyncio.TimeoutError:
            logger.warning("Timed out waiting for FullEnrich worker shutdown; cancelling task.")
            worker_task.cancel()
            await asyncio.gather(worker_task, return_exceptions=True)


app = FastAPI(
    title="FoundryMatch FullEnrich Webhook Worker",
    version="1.0.0",
    lifespan=lifespan,
)


@app.get("/healthz", include_in_schema=False)
async def healthz() -> Dict[str, Any]:
    return {"ok": True}


@app.get("/readyz", include_in_schema=False)
async def readyz():
    worker_task = getattr(app.state, "worker_task", None)
    worker = getattr(app.state, "worker", None)
    if worker_task is None or worker is None:
        return JSONResponse(status_code=503, content={"ok": False, "error": "worker_not_initialized"})
    if worker_task.done():
        return JSONResponse(status_code=503, content={"ok": False, "error": "worker_stopped"})
    return {
        "ok": True,
        "queue": FULLENRICH_QUEUE,
        "concurrency": int(worker.concurrency),
    }
