"""Work Queue API — monitor and manage the persistent job queue."""

from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException, Request

log = logging.getLogger(__name__)

router = APIRouter(prefix="/work-queue", tags=["work-queue"])


@router.get("")
async def get_status(request: Request) -> dict:
    """Get work queue status: LLM health, pending jobs, counts."""
    wq = getattr(request.app.state, "work_queue", None)
    if not wq:
        return {"error": "Work queue not initialized"}
    return await wq.get_status()


@router.get("/history")
async def get_history(request: Request, limit: int = 50) -> list[dict]:
    """Get recently completed/dead_letter jobs."""
    wq = getattr(request.app.state, "work_queue", None)
    if not wq:
        return []
    return await wq.get_history(limit=limit)


@router.post("/retry/{job_id}")
async def retry_job(request: Request, job_id: int) -> dict:
    """Retry a failed or dead_letter job."""
    wq = getattr(request.app.state, "work_queue", None)
    if not wq:
        raise HTTPException(status_code=503, detail="Work queue not initialized")
    ok = await wq.retry_job(job_id)
    if not ok:
        raise HTTPException(status_code=404, detail="Job not found or not in retryable state")
    return {"status": "queued", "job_id": job_id}


@router.post("/retry-all")
async def retry_all(request: Request) -> dict:
    """Retry all failed/dead_letter jobs."""
    wq = getattr(request.app.state, "work_queue", None)
    if not wq:
        raise HTTPException(status_code=503, detail="Work queue not initialized")
    count = await wq.retry_all()
    return {"status": "queued", "count": count}


@router.delete("/{job_id}")
async def cancel_job(request: Request, job_id: int) -> dict:
    """Cancel a pending/failed job."""
    wq = getattr(request.app.state, "work_queue", None)
    if not wq:
        raise HTTPException(status_code=503, detail="Work queue not initialized")
    ok = await wq.cancel_job(job_id)
    if not ok:
        raise HTTPException(status_code=404, detail="Job not found or not cancellable")
    return {"status": "cancelled", "job_id": job_id}


@router.delete("/completed/clear")
async def clear_completed(request: Request, older_than_days: int = 7) -> dict:
    """Remove completed jobs older than N days."""
    wq = getattr(request.app.state, "work_queue", None)
    if not wq:
        raise HTTPException(status_code=503, detail="Work queue not initialized")
    count = await wq.clear_completed(older_than_days)
    return {"status": "cleared", "count": count}


@router.get("/llm-health")
async def llm_health(request: Request) -> dict:
    """Get current LLM health status and active model."""
    wq = getattr(request.app.state, "work_queue", None)
    llm = getattr(request.app.state, "llm", None)

    result: dict = {
        "healthy": True,
        "active_model": "unknown",
        "last_error": "",
    }

    if wq:
        result["healthy"] = wq.llm_healthy
        result["active_model"] = wq.active_model

    if llm:
        result["active_model"] = getattr(llm, "model_name", getattr(llm, "_model", result["active_model"]))
        result["last_error"] = getattr(llm, "last_error", "")
        result["provider_healthy"] = getattr(llm, "healthy", True)

    if wq:
        status = await wq.get_status()
        result["pending_jobs"] = status.get("total_pending", 0)

    return result
