from pathlib import Path
from typing import Optional

from fastapi import APIRouter, Query, Request
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates

from app.services.analytics_data import collect_analytics

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


@router.get("")
async def analytics_page(request: Request):
    initial = collect_analytics({})
    return templates.TemplateResponse(
        "analytics.html",
        {"request": request, "page_title": "Analytics", "initial_data": initial},
    )


@router.get("/api/data")
async def analytics_api(
    chain: Optional[str] = None,
    province: Optional[str] = None,
    stage: Optional[str] = None,
    agent: Optional[str] = None,
    days: int = Query(90, ge=7, le=365),
):
    filters = {"chain": chain, "province": province, "stage": stage, "agent": agent, "days": days}
    filters = {k: v for k, v in filters.items() if v is not None and v != ""}
    return JSONResponse(collect_analytics(filters))
