from __future__ import annotations

from typing import Any

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field

from niannian import NianNian
from niannian.agents.loop_registry import AgentLoopNotConfigured
from niannian.http.core_auth import require_baseline_owner, require_core_access


class LoopRunBody(BaseModel):
    context: dict[str, Any] = Field(default_factory=dict)


def create_cognitive_router(nn: NianNian) -> APIRouter:
    router = APIRouter(tags=["cognitive"])

    @router.get("/v1/cognitive/loops")
    def list_loops(_role: str = Depends(require_core_access)):
        reg = nn._agents.loop_registry
        return {"loops": reg.list_loops()}

    @router.post("/v1/cognitive/loops/{loop_id}/run")
    def run_loop(
        loop_id: str,
        body: LoopRunBody | None = None,
        _role: str = Depends(require_baseline_owner),
    ):
        reg = nn._agents.loop_registry
        try:
            run = reg.start(loop_id, context=(body.context if body else None))
        except AgentLoopNotConfigured as exc:
            msg = str(exc)
            if "disabled" in msg or "not supported" in msg:
                raise HTTPException(
                    status_code=409,
                    detail={"code": "loop_not_available", "message": msg},
                ) from exc
            raise HTTPException(
                status_code=404,
                detail={"code": "loop_not_found", "message": msg},
            ) from exc
        return run.to_dict()

    return router
