from typing import List, Optional

from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel

from .. import jobs
from ..audit_store import AuditStore
from ..db import get_store
from ..runs_store import RunStore
from ..tasks import enrich_job, recheck_job

router = APIRouter()


@router.get("/keys")
def list_keys(
    category: Optional[str] = None,
    provider: Optional[str] = None,
    status: Optional[str] = None,
    variable: Optional[str] = None,
    repo: Optional[str] = None,
    run: Optional[str] = Query(None, description="keys whose most recent run was this run id"),
    noted: bool = Query(False, description="only keys that carry a note"),
    q: Optional[str] = Query(None, description="substring of the key, its masked form, or its note"),
    sort: str = "last_seen",
    order: str = Query("desc", pattern="^(asc|desc)$"),
    page: int = Query(1, ge=1),
    limit: int = Query(50, ge=1, le=500),
):
    filters = {"category": category, "provider_id": provider, "status": status,
               "variable": variable, "repo": repo, "run": run, "noted": noted, "q": q}
    rows, total = get_store().query_page(
        filters, sort=sort, order=-1 if order == "desc" else 1, page=page, limit=limit)
    return {"rows": rows, "total": total, "page": page, "limit": limit}


@router.get("/keys/{key}")
def get_key(key: str):
    doc = get_store().get_by_key(key)
    if not doc:
        raise HTTPException(status_code=404, detail="key not found")
    return doc


class NoteBody(BaseModel):
    note: str = ""


@router.post("/keys/{key}/note")
def set_note(key: str, body: NoteBody):
    """Attach or clear a free-text note on a key (searchable, survives rechecks)."""
    if not get_store().set_note(key, body.note.strip()):
        raise HTTPException(status_code=404, detail="key not found")
    return {"ok": True}


class RecheckBody(BaseModel):
    keys: Optional[List[str]] = None   # explicit selection; when set, filters are ignored
    category: Optional[str] = None     # otherwise recheck everything matching these filters
    provider: Optional[str] = None
    status: Optional[str] = None
    variable: Optional[str] = None
    repo: Optional[str] = None
    run: Optional[str] = None
    noted: bool = False
    q: Optional[str] = None


@router.post("/keys/recheck")
def recheck(body: RecheckBody):
    """Recheck either the selected keys, or everything matching the filters. Watch the run's events."""
    filters = {"category": body.category, "provider_id": body.provider, "status": body.status,
               "variable": body.variable, "repo": body.repo, "run": body.run,
               "noted": body.noted, "q": body.q}
    rid = RunStore().create("recheck", [], "-")
    AuditStore().record("recheck.started", {
        "run": rid, "selected": len(body.keys) if body.keys else None, "filters": filters})
    jobs.start_job(rid, recheck_job(rid, filters, keys=body.keys))
    return {"run_id": rid}


@router.post("/keys/enrich")
def enrich(body: RecheckBody):
    """Capture capability (model access) + usage/tier for keys — a quick list-check, no generation
    and no status change. Selected keys, or everything matching the filters (defaults to alive keys)."""
    filters = {"category": body.category, "provider_id": body.provider, "status": body.status,
               "variable": body.variable, "repo": body.repo, "run": body.run,
               "noted": body.noted, "q": body.q}
    rid = RunStore().create("enrich", [], "-")
    AuditStore().record("enrich.started", {
        "run": rid, "selected": len(body.keys) if body.keys else None, "filters": filters})
    jobs.start_job(rid, enrich_job(rid, filters, keys=body.keys))
    return {"run_id": rid}
