from pathlib import Path
from fastapi import APIRouter, Request
from fastapi.templating import Jinja2Templates
from app.db import fetch_all

router = APIRouter(prefix="/voice", tags=["voice"])
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 voice_page(request: Request):
    events = []
    try:
        events = _iso_rows(fetch_all(
            """SELECT id, agent_name, title, body, status, created_at FROM agent_events
               WHERE channel = 'voice' OR event_type LIKE 'voice%%' ORDER BY created_at DESC LIMIT 25"""
        ))
    except Exception:
        events = []
    return templates.TemplateResponse("voice.html", {"request": request, "page_title": "Voice", "voice_events": events})
