"""Formal query-generation preview API routes."""
from __future__ import annotations

from typing import Any
from uuid import UUID

from fastapi import APIRouter, Depends, Query

from acquisition.queries.builder import QueryBuildOptions, TREES, build_creation_query_batch
from app.dependencies import _env_file, get_acquisition_repository
from app.routes.acquisition import _normalize_query_detail
from core.config import Settings

router = APIRouter(prefix="/api/query-generation", tags=["query-generation"])


def _summary(generated: dict[str, Any]) -> dict[str, Any]:
    families = generated.get("families") or []
    return {
        "family_count": len(families),
        "family_keys": [family.get("key") for family in families],
        "query_count": sum(len(family.get("items") or []) for family in families),
        "kept_count": sum(
            1
            for family in families
            for item in family.get("items") or []
            if item.get("keep", True)
        ),
    }


@router.get("/preview")
def query_generation_preview(
    per: int = Query(default=0, ge=0, le=10000),
    batch_n: int = Query(default=0, ge=0, le=1000),
    dry: bool = Query(default=True),
) -> dict[str, Any]:
    """Preview the currently active formal query families without writing DB rows."""

    settings = Settings.from_env(_env_file())
    generated = build_creation_query_batch(
        settings,
        tree_path=TREES,
        options=QueryBuildOptions(
            per=per,
            batch_n=batch_n,
            dry=dry,
            active_family_keys=("f1", "f2"),
        ),
    )
    generated["summary"] = _summary(generated)
    return generated


@router.get("/latest-singleton")
def latest_singleton_overview(repo: Any = Depends(get_acquisition_repository)) -> dict[str, Any]:
    """Return links from the query preview board to the latest real singleton run."""

    getter = getattr(repo, "get_latest_singleton_overview", None)
    if getter is None:
        return {"batch": None, "run": None, "queries": [], "decoded_items": []}
    return getter()


@router.get("/latest/queries/{query_id}")
def latest_query_detail(
    query_id: UUID,
    repo: Any = Depends(get_acquisition_repository),
) -> dict[str, Any]:
    """Return search material for one query in the latest real query board batch."""

    overview_getter = getattr(repo, "get_latest_singleton_overview", None)
    detail_getter = getattr(repo, "get_query_detail_for_batch", None)
    if overview_getter is None or detail_getter is None:
        return {"query": None, "jobs": [], "items": [], "platforms": {}}
    overview = overview_getter()
    batch = overview.get("batch")
    batch_id = batch.get("id") if isinstance(batch, dict) else getattr(batch, "id", None)
    if batch_id is None:
        return {"query": None, "jobs": [], "items": [], "platforms": {}}
    return _normalize_query_detail(detail_getter(batch_id=batch_id, query_id=query_id))
