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

router = APIRouter(prefix="/clients", tags=["clients"])
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 clients_page(request: Request):
    rows = []
    try:
        rows = _iso_rows(fetch_all(
            """SELECT id, name, contact, email, stage, sector, mrr_estimate, notes, created_at, updated_at
               FROM clients ORDER BY updated_at DESC NULLS LAST, created_at DESC LIMIT 200"""
        ))
    except Exception:
        rows = []
    return templates.TemplateResponse("clients.html", {"request": request, "page_title": "Clients", "clients": rows})
