from pathlib import Path
from fastapi import APIRouter, Form, Request
from fastapi.templating import Jinja2Templates

from app.db import fetch_all
from app.services.herman import AGENTS, chat, generate_briefing

router = APIRouter(prefix="/herman", tags=["herman"])
BASE_DIR = Path(__file__).resolve().parent.parent.parent
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))

def _iso_rows(rows: list) -> list:
    for row in rows:
        for key, val in list(row.items()):
            if hasattr(val, "isoformat"):
                row[key] = val.isoformat()
    return rows

@router.get("")
async def herman_page(request: Request):
    history = []
    try:
        history = _iso_rows(fetch_all(
            """SELECT id, agent_name, title, body, metadata, created_at FROM agent_events
               WHERE channel IN ('herman','dashboard','browser','voice') ORDER BY created_at DESC LIMIT 40"""
        ))
    except Exception:
        history = []
    return templates.TemplateResponse(
        "herman_chat.html",
        {"request": request, "page_title": "Herman", "agents": AGENTS, "history": history, "last_reply": None, "last_agent": None},
    )

@router.post("/chat")
async def herman_chat(request: Request, message: str = Form(...)):
    result = await chat(message)
    history = []
    try:
        history = _iso_rows(fetch_all(
            """SELECT id, agent_name, title, body, metadata, created_at FROM agent_events
               WHERE channel IN ('herman','dashboard','browser','voice') ORDER BY created_at DESC LIMIT 40"""
        ))
    except Exception:
        history = []
    return templates.TemplateResponse(
        "herman_chat.html",
        {
            "request": request,
            "page_title": "Herman",
            "agents": AGENTS,
            "history": history,
            "last_reply": result.get("reply"),
            "last_agent": result.get("agent_label"),
            "user_message": message,
        },
    )

@router.post("/briefing")
async def herman_briefing_page(request: Request):
    content = await generate_briefing()
    history = []
    try:
        history = _iso_rows(fetch_all(
            """SELECT id, agent_name, title, body, metadata, created_at FROM agent_events
               WHERE channel IN ('herman','dashboard','browser','voice') ORDER BY created_at DESC LIMIT 40"""
        ))
    except Exception:
        history = []
    return templates.TemplateResponse(
        "herman_chat.html",
        {
            "request": request,
            "page_title": "Herman",
            "agents": AGENTS,
            "history": history,
            "last_reply": content,
            "last_agent": "Herman · Briefing",
        },
    )
