from pathlib import Path

from fastapi import APIRouter, Form, Request
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates

from app.db import execute, fetch_all

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

BASE_DIR = Path(__file__).resolve().parent.parent.parent
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))

AGENT_STATUSES = [
    {"name": "Herman", "role": "Co-CEO · Takenverdeler", "color": "cyan"},
    {"name": "Sales", "role": "Pipeline", "color": "purple"},
    {"name": "Marketing", "role": "Social & Content", "color": "amber"},
    {"name": "Ops", "role": "Operations", "color": "green"},
]


@router.get("")
async def agents_page(request: Request):
    active_tab = request.query_params.get("tab", "souls")
    if active_tab not in {"souls", "mesh", "terminals", "approvals"}:
        active_tab = "souls"
    events: list = []
    try:
        events = fetch_all(
            """
            SELECT id, agent_name, event_type, title, body, status, created_at
            FROM agent_events
            ORDER BY created_at DESC
            LIMIT 100
            """
        )
        for ev in events:
            if ev.get("created_at"):
                ev["created_at"] = ev["created_at"].isoformat()
    except Exception:
        events = []

    return templates.TemplateResponse(
        "agents.html",
        {
            "request": request,
            "page_title": "Agents",
            "active_tab": active_tab,
            "agents": AGENT_STATUSES,
            "events": events,
        },
    )


@router.post("/approve/{event_id}")
async def approve_event(event_id: int, next_url: str = Form("/")):
    try:
        execute(
            """
            UPDATE agent_events
            SET status = 'approved'
            WHERE id = %s
            """,
            (event_id,),
        )
    except Exception:
        pass
    return RedirectResponse(url=next_url, status_code=303)


@router.post("/reject/{event_id}")
async def reject_event(event_id: int, next_url: str = Form("/")):
    try:
        execute(
            """
            UPDATE agent_events
            SET status = 'rejected'
            WHERE id = %s
            """,
            (event_id,),
        )
    except Exception:
        pass
    return RedirectResponse(url=next_url, status_code=303)
