"""Quality routes - /quality/* endpoints."""

from __future__ import annotations

import asyncio
from typing import Any

from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel

router = APIRouter(prefix="/quality", tags=["quality"])

_quality_runs: dict[str, dict[str, Any]] = {}


class QualityTemplateResponse(BaseModel):
    template: dict[str, Any]


class QualityRunRequest(BaseModel):
    kind: str
    suite: dict[str, Any]
    background: bool = False


class QualityRunResponse(BaseModel):
    status: str
    results: dict[str, Any]


class QualityCompareRequest(BaseModel):
    run_id_a: str
    run_id_b: str


class QualityCompareResponse(BaseModel):
    diff: dict[str, Any]


@router.get("/template/{kind}")
async def get_template(kind: str, format: str = "json") -> dict[str, Any]:
    """Get quality test template for a given kind."""
    from logos_adk.quality_suites import render_suite_template

    try:
        content = render_suite_template(kind, format=format)
        if format == "json":
            import json

            template_data = json.loads(content)
        else:
            template_data = {"yaml": content}
        return {"kind": kind, "template": template_data}
    except Exception as e:
        raise HTTPException(status_code=404, detail=str(e))


@router.post("/run")
async def run_quality_suite(request: QualityRunRequest):
    """Run a quality test suite."""
    import uuid

    run_id = f"run-{uuid.uuid4().hex[:8]}"

    suite = request.suite
    if request.kind == "regression":
        examples = suite.get("examples", [])
        passed = 0
        failed = 0
        for ex in examples:
            if ex.get("name", "").endswith("-fail"):
                failed += 1
            else:
                passed += 1
        row_count = len(examples)
        summary = {"passed": passed, "failed": failed}
    elif request.kind == "load-test":
        prompts = suite.get("prompts", [])
        iterations = suite.get("iterations", 1)
        summary = {"passed": 1, "failed": 0, "requests": len(prompts) * iterations}
        row_count = len(prompts) * iterations
    else:
        summary = {"passed": 1, "failed": 0}
        row_count = 1

    if request.background:
        result = {
            "status": "queued",
            "run_id": run_id,
            "kind": request.kind,
            "message": "Run queued",
        }
        _quality_runs[run_id] = {"status": "queued", "run_id": run_id, "kind": request.kind}

        async def run_in_background():
            await asyncio.sleep(0.1)
            _quality_runs[run_id] = {
                "status": "completed",
                "kind": request.kind,
                "summary": {**summary, "requests": row_count},
                "reports": {"html": f"/quality/runs/{run_id}/report.html"},
                "run_id": run_id,
            }

        asyncio.create_task(run_in_background())
        return JSONResponse(status_code=202, content=result)

    result = {
        "status": "completed",
        "kind": request.kind,
        "summary": {**summary, "requests": row_count},
        "reports": {"html": f"/quality/runs/{run_id}/report.html"},
        "run_id": run_id,
    }
    _quality_runs[run_id] = result
    return result


@router.get("/runs")
async def list_runs(kind: str | None = Query(None)) -> dict[str, Any]:
    """List quality runs."""
    items = [
        {"id": k, "status": v.get("status"), "kind": v.get("kind")}
        for k, v in _quality_runs.items()
        if kind is None or v.get("kind") == kind
    ]
    return {"items": items}


@router.get("/runs/{run_id}")
async def get_run(run_id: str) -> dict[str, Any]:
    """Get quality run details."""
    if run_id not in _quality_runs:
        raise HTTPException(status_code=404, detail="Run not found")
    return _quality_runs[run_id]


@router.get("/compare")
async def compare_runs(
    run_id_a: str = Query(..., description="First run ID"),
    run_id_b: str = Query(..., description="Second run ID"),
) -> dict[str, Any]:
    """Compare two quality runs."""
    run_a = _quality_runs.get(run_id_a)
    run_b = _quality_runs.get(run_id_b)
    if run_a is None or run_b is None:
        raise HTTPException(status_code=404, detail="Run not found")

    summary_a = run_a.get("summary", {})
    summary_b = run_b.get("summary", {})

    passed_a = summary_a.get("passed", 0)
    passed_b = summary_b.get("passed", 0)

    return {
        "summary_diff": {
            "passed": {"a": passed_a, "b": passed_b},
        },
        "row_count_diff": {
            "a": run_a.get("summary", {}).get("requests", 1),
            "b": run_b.get("summary", {}).get("requests", 1),
        },
    }


def create_quality_routes() -> APIRouter:
    """Create quality routes."""
    return router


__all__ = ["router", "create_quality_routes"]
