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

router = APIRouter(prefix="/deals", tags=["deals"])
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 deals_page(request: Request):
    rows = []
    try:
        rows = _iso_rows(fetch_all(
            """SELECT d.id, d.title, d.value, d.stage, d.agent_owner, d.next_action, d.deadline,
                      d.created_at, c.name AS client_name
               FROM deals d LEFT JOIN clients c ON c.id = d.client_id
               ORDER BY d.updated_at DESC NULLS LAST LIMIT 200"""
        ))
    except Exception:
        rows = []
    stages = {}
    for r in rows:
        st = r.get("stage") or "unknown"
        stages.setdefault(st, []).append(r)
    return templates.TemplateResponse("deals.html", {"request": request, "page_title": "Deals", "deals": rows, "kanban": stages})
