from __future__ import annotations
from collections import defaultdict
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from app.web.deps import templates, sb

router = APIRouter()

@router.get("/sync", response_class=HTMLResponse)
async def sync_index(request: Request):
    batches = sb.table("ingest_batches").select("*").order("started_at", desc=True).limit(20).execute().data or []
    if not batches:
        return templates.TemplateResponse("sync/index.html", {
            "request": request, "rows": [], "event_stats": {}, "pending_stats": {}
        })

    batch_ids = [b["batch_id"] for b in batches if b.get("batch_id")]
    ev = sb.table("gov_staff_events").select("batch_id,event_type").in_("batch_id", batch_ids).execute().data or []
    event_stats = defaultdict(lambda: defaultdict(int))
    for e in ev:
        event_stats[e["batch_id"]][e["event_type"]] += 1

    dec = sb.table("match_decisions").select("batch_id,decision").in_("batch_id", batch_ids).execute().data or []
    pending_stats = defaultdict(int)
    for d in dec:
        if d.get("decision") == "PENDING":
            pending_stats[d["batch_id"]] += 1

    return templates.TemplateResponse("sync/index.html", {
        "request": request, "rows": batches,
        "event_stats": dict(event_stats), "pending_stats": dict(pending_stats),
    })
