"""
Cloud Run service wrapper for the Gmail history 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.workers.gmail_history_worker import (
    GMAIL_HISTORY_QUEUE,
    GmailHistoryWorker,
)

logger = logging.getLogger(__name__)


def _resolve_worker_concurrency() -> int:
    raw = os.getenv("GMAIL_HISTORY_WORKER_CONCURRENCY")
    if raw:
        try:
            return max(int(raw), 1)
        except ValueError:
            logger.warning(
                "Invalid GMAIL_HISTORY_WORKER_CONCURRENCY=%r; using default.",
                raw,
            )
    return 3


@asynccontextmanager
async def lifespan(app: FastAPI):
    worker = GmailHistoryWorker(
        concurrency=_resolve_worker_concurrency(),
        manage_signals=False,
    )
    worker_task = asyncio.create_task(worker.start(), name="gmail-history-worker")
    app.state.worker = worker
    app.state.worker_task = worker_task
    logger.info(
        "Started Gmail history worker service (queue=%s, concurrency=%d).",
        GMAIL_HISTORY_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 Gmail worker shutdown; cancelling task."
            )
            worker_task.cancel()
            await asyncio.gather(worker_task, return_exceptions=True)


app = FastAPI(
    title="FoundryMatch Gmail History 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": GMAIL_HISTORY_QUEUE,
        "concurrency": int(worker.concurrency),
    }
