"""Admin endpoints — observability layer configuration + health.

Surfaces the knobs that power the accountability layer so a user can
monitor and tune them without editing code. Meant for the /admin page:

    GET  /api/admin/overview       — one-shot snapshot: decisions health,
                                      rate-limit snapshot, retention config
    GET  /api/admin/rate-limits    — status of every configured rate-limit scope
    POST /api/admin/rate-limits/reset — clear tracked buckets for a scope

These are read-mostly. Mutating rate-limit policies at runtime is
deliberately NOT supported — the policies live in code so a user can't
accidentally raise their own limit on a sensitive endpoint from the UI.
If you need a new policy, ship it in `rate_limit.get_limiter()`.
"""

from __future__ import annotations

from fastapi import APIRouter, Request
from pydantic import BaseModel

from agntspace.infra.rate_limit import get_limiter

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


class _ResetRequest(BaseModel):
    scope: str
    caller: str | None = None


@router.get("/overview")
async def admin_overview(request: Request) -> dict:
    """One-shot snapshot combining decision health + rate-limit state + retention."""
    decisions = getattr(request.app.state, "decisions", None)
    evolution = getattr(request.app.state, "evolution", None)
    limiter = get_limiter()

    health = decisions.health() if decisions is not None else {"status": "unavailable"}
    evolution_health = (
        evolution.health() if evolution is not None and hasattr(evolution, "health")
        else {"initialized": False, "status": "unavailable"}
    )

    rate_limits: list[dict] = []
    for scope in ("privacy_forget", "privacy_export", "decisions_prune"):
        rate_limits.append(limiter.snapshot(scope))

    return {
        "decision_health": health,
        "evolution_health": evolution_health,
        "rate_limits": rate_limits,
    }


@router.get("/rate-limits")
async def rate_limit_status(request: Request) -> dict:
    """Return the configured rate-limit policies + active bucket counts."""
    limiter = get_limiter()
    scopes = sorted(limiter._policies.keys())  # noqa: SLF001
    return {
        "scopes": [limiter.snapshot(s) for s in scopes],
    }


@router.post("/rate-limits/reset")
async def rate_limit_reset(request: Request, body: _ResetRequest) -> dict:
    """Clear tracked buckets for a scope (and optionally a single caller).

    Use case: the user got themselves locked out during a misconfigured
    script test and wants to reset without restarting the server.
    """
    limiter = get_limiter()
    limiter.reset(scope=body.scope, caller=body.caller)
    return {"ok": True, "scope": body.scope, "caller": body.caller or "all"}
