"""FastAPI app for the API Hunt management tool.

Run locally:
    venv/Scripts/python.exe -m uvicorn api.main:app --reload --port 8000
"""
from dotenv import load_dotenv

load_dotenv()  # make .env available before settings/stores read it

import asyncio  # noqa: E402
from contextlib import asynccontextmanager  # noqa: E402

from fastapi import Depends, FastAPI  # noqa: E402
from fastapi.middleware.cors import CORSMiddleware  # noqa: E402

from . import jobs  # noqa: E402
from .auth import require_token  # noqa: E402
from .config import settings  # noqa: E402
from .routers import keys, runs, stats  # noqa: E402


@asynccontextmanager
async def lifespan(_app: FastAPI):
    # Capture the running loop so worker threads can push SSE events back onto it.
    jobs.set_loop(asyncio.get_running_loop())
    # In-process jobs don't survive a restart, so a run left "running" is orphaned — but only if
    # nothing is still driving it. A live run heartbeats as it works; a peer instance sharing this
    # DB may own it. So interrupt only runs whose heartbeat has gone stale (or never beat).
    try:
        from datetime import datetime, timedelta, timezone
        from .db import get_store
        cutoff = datetime.now(timezone.utc) - timedelta(seconds=90)
        get_store().coll.database["runs"].update_many(
            {"status": "running",
             "$or": [{"heartbeat": {"$lt": cutoff}}, {"heartbeat": {"$exists": False}}]},
            {"$set": {"status": "interrupted"}})
    except Exception:  # noqa: BLE001
        pass
    yield


app = FastAPI(title="API Hunt", version="0.1.0", lifespan=lifespan)

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_list,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/api/health")
def health():
    return {"ok": True}


# Everything else requires the bearer token.
app.include_router(stats.router, prefix="/api", dependencies=[Depends(require_token)])
app.include_router(keys.router, prefix="/api", dependencies=[Depends(require_token)])
app.include_router(runs.router, prefix="/api", dependencies=[Depends(require_token)])

# In a container build the console is bundled to web/dist and served from the same origin, so the
# SPA's /api calls need no CORS and no separate web server. Mounted last, so /api wins. Absent in
# local dev (Vite serves the SPA and proxies /api), so this is a no-op there.
from pathlib import Path  # noqa: E402
from fastapi.staticfiles import StaticFiles  # noqa: E402

_DIST = Path(__file__).resolve().parent.parent / "web" / "dist"
if _DIST.is_dir():
    app.mount("/", StaticFiles(directory=str(_DIST), html=True), name="spa")
