"""Three-Strike Detector dashboard routes.

Provides JSON API endpoints for inspecting and managing the three-strike
detector state.

Refs: #962
"""

import logging
from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from timmy.sovereignty.three_strike import CATEGORIES, get_detector

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/sovereignty/three-strike", tags=["three-strike"])


class RecordRequest(BaseModel):
    category: str
    key: str
    metadata: dict[str, Any] = {}


class AutomationRequest(BaseModel):
    artifact_path: str


@router.get("")
async def list_strikes() -> dict[str, Any]:
    """Return all strike records."""
    detector = get_detector()
    records = detector.list_all()
    return {
        "records": [
            {
                "category": r.category,
                "key": r.key,
                "count": r.count,
                "blocked": r.blocked,
                "automation": r.automation,
                "first_seen": r.first_seen,
                "last_seen": r.last_seen,
            }
            for r in records
        ],
        "categories": sorted(CATEGORIES),
    }


@router.get("/blocked")
async def list_blocked() -> dict[str, Any]:
    """Return only blocked (category, key) pairs."""
    detector = get_detector()
    records = detector.list_blocked()
    return {
        "blocked": [
            {
                "category": r.category,
                "key": r.key,
                "count": r.count,
                "automation": r.automation,
                "last_seen": r.last_seen,
            }
            for r in records
        ]
    }


@router.post("/record")
async def record_strike(body: RecordRequest) -> dict[str, Any]:
    """Record a manual action.  Returns strike state; 409 when blocked."""
    from timmy.sovereignty.three_strike import ThreeStrikeError

    detector = get_detector()
    try:
        record = detector.record(body.category, body.key, body.metadata)
        return {
            "category": record.category,
            "key": record.key,
            "count": record.count,
            "blocked": record.blocked,
            "automation": record.automation,
        }
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc)) from exc
    except ThreeStrikeError as exc:
        raise HTTPException(
            status_code=409,
            detail={
                "error": "three_strike_block",
                "message": str(exc),
                "category": exc.category,
                "key": exc.key,
                "count": exc.count,
            },
        ) from exc


@router.post("/{category}/{key}/automation")
async def register_automation(category: str, key: str, body: AutomationRequest) -> dict[str, bool]:
    """Register an automation artifact to unblock a (category, key) pair."""
    detector = get_detector()
    detector.register_automation(category, key, body.artifact_path)
    return {"success": True}


@router.get("/{category}/{key}/events")
async def get_strike_events(category: str, key: str, limit: int = 50) -> dict[str, Any]:
    """Return the individual strike events for a (category, key) pair."""
    detector = get_detector()
    events = detector.get_events(category, key, limit=limit)
    return {"category": category, "key": key, "events": events}
