"""Retail intelligence map page + API proxy."""
from __future__ import annotations

import os
from typing import Any, Optional

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

router = APIRouter()
BASE = Path(__file__).resolve().parent.parent.parent
templates = Jinja2Templates(directory=str(BASE / "templates"))
TOOLS = os.getenv("TOOLS_API_URL", "http://tools-api:8700").rstrip("/")


async def _tools_get(path: str, params: Optional[dict] = None) -> Any:
    async with httpx.AsyncClient(timeout=60) as client:
        resp = await client.get(f"{TOOLS}{path}", params=params or {})
        resp.raise_for_status()
        return resp.json()


@router.get("/retail")
async def retail_page(request: Request):
    stats = await _tools_get("/retail/stats")
    filters = await _tools_get("/retail/filters")
    enrich = await _tools_get("/retail/enrich/status")
    recs = await _tools_get("/recommendations/pending", {"limit": 5})
    return templates.TemplateResponse(
        "retail.html",
        {
            "request": request,
            "stats": stats,
            "filters": filters,
            "enrichment": enrich,
            "recommendations": recs.get("items", []),
        },
    )


@router.get("/api/retail/stats")
async def api_retail_stats(request: Request):
    return JSONResponse(await _tools_get("/retail/stats", dict(request.query_params)))


@router.get("/api/retail/filters")
async def api_retail_filters():
    return JSONResponse(await _tools_get("/retail/filters"))


@router.get("/api/retail/map")
async def api_retail_map(request: Request):
    return JSONResponse(await _tools_get("/retail/map", dict(request.query_params)))


@router.get("/api/retail/supermarkets/{store_id}")
async def api_retail_store(store_id: int):
    return JSONResponse(await _tools_get(f"/retail/supermarkets/{store_id}"))


@router.post("/api/retail/enrich")
async def api_retail_enrich(limit: int = Query(50, ge=1, le=200)):
    async with httpx.AsyncClient(timeout=300) as client:
        resp = await client.post(f"{TOOLS}/retail/enrich", params={"limit": limit})
        resp.raise_for_status()
        return JSONResponse(resp.json())
