"""Agent insights API — the agent's proactive observations and suggestions."""

from __future__ import annotations

from fastapi import APIRouter, HTTPException, Request

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


@router.get("")
async def get_insights(request: Request) -> dict:
    """Get current agent insights snapshot."""
    engine = getattr(request.app.state, "insights_engine", None)
    if not engine:
        return {"insights": [], "generated_at": "", "next_refresh": "", "total": 0, "dismissed_count": 0}
    return engine.to_dict()


@router.post("/refresh")
async def refresh_insights(request: Request) -> dict:
    """Force a fresh insights generation cycle."""
    engine = getattr(request.app.state, "insights_engine", None)
    if not engine:
        raise HTTPException(status_code=503, detail="Insights engine not initialized")
    await engine.generate()
    return engine.to_dict()


@router.post("/{insight_id}/dismiss")
async def dismiss_insight(request: Request, insight_id: str) -> dict:
    """Dismiss an insight so it won't reappear."""
    engine = getattr(request.app.state, "insights_engine", None)
    if not engine:
        raise HTTPException(status_code=503, detail="Insights engine not initialized")
    ok = engine.dismiss(insight_id)
    if not ok:
        raise HTTPException(status_code=404, detail=f"Insight not found: {insight_id}")
    return {"dismissed": True, "id": insight_id}


@router.get("/nudges")
async def get_chat_nudges(request: Request, max_count: int = 3) -> dict:
    """Get top insights formatted for chat prompt injection."""
    engine = getattr(request.app.state, "insights_engine", None)
    if not engine:
        return {"nudges": "", "count": 0}
    nudges = engine.get_chat_nudges(max_count=max_count)
    count = len([i for i in engine.get_snapshot().insights if not i.dismissed])
    return {"nudges": nudges, "count": count}
