from fastapi.testclient import TestClient

import grantflow.api.routes.jobs as jobs_routes
from grantflow.api import runtime_state
from grantflow.api.app import app

client = TestClient(app)


def stub_generate_preflight(monkeypatch, mode: str = "warn") -> None:
    monkeypatch.setattr(
        jobs_routes,
        "_build_generate_preflight",
        lambda donor_id, strategy, client_metadata, **kwargs: {
            "donor_id": donor_id,
            "risk_level": "low",
            "grounding_risk_level": "low",
            "go_ahead": True,
            "warning_count": 0,
            "warnings": [],
            "retrieval_namespace": "usaid_ads201",
            "namespace_empty": False,
            "grounding_policy": {
                "mode": mode,
                "risk_level": "low",
                "blocking": False,
                "go_ahead": True,
                "summary": "readiness_signals_ok",
                "reasons": ["sufficient_readiness_signals"],
            },
        },
    )


def empty_vector_query(namespace, query_texts, n_results=5, where=None, top_k=None):
    return {"documents": [[]], "metadatas": [[]], "ids": [[]]}


def seed_grounding_ingest_audit_store() -> None:
    runtime_state.INGEST_AUDIT_STORE.clear()
    for event in (
        {
            "event_id": "seed-gate-pass-1",
            "ts": "2026-03-01T09:00:00+00:00",
            "donor_id": "usaid",
            "namespace": "usaid_ads201",
            "filename": "ads-policy-seed.pdf",
            "content_type": "application/pdf",
            "metadata": {"doc_family": "donor_policy", "source_type": "donor_guidance"},
            "result": {"chunks_ingested": 10},
        },
        {
            "event_id": "seed-gate-pass-2",
            "ts": "2026-03-01T09:01:00+00:00",
            "donor_id": "usaid",
            "namespace": "usaid_ads201",
            "filename": "responsible-ai-seed.pdf",
            "content_type": "application/pdf",
            "metadata": {"doc_family": "responsible_ai_guidance", "source_type": "reference_guidance"},
            "result": {"chunks_ingested": 8},
        },
        {
            "event_id": "seed-gate-pass-3",
            "ts": "2026-03-01T09:02:00+00:00",
            "donor_id": "usaid",
            "namespace": "usaid_ads201",
            "filename": "country-context-seed.pdf",
            "content_type": "application/pdf",
            "metadata": {"doc_family": "country_context", "source_type": "country_context"},
            "result": {"chunks_ingested": 7},
        },
    ):
        runtime_state.INGEST_AUDIT_STORE.append(event)


def seeded_vector_query(namespace, query_texts, n_results=5, where=None, top_k=None):
    query_rows = query_texts if isinstance(query_texts, list) and query_texts else [str(query_texts or "")]
    docs: list[list[str]] = []
    metadatas: list[list[dict[str, object]]] = []
    ids: list[list[str]] = []
    distances: list[list[float]] = []
    limit = max(1, min(int(n_results or top_k or 5), 4))
    for q_idx, query in enumerate(query_rows):
        docs_row: list[str] = []
        metas_row: list[dict[str, object]] = []
        ids_row: list[str] = []
        distances_row: list[float] = []
        for hit_idx in range(limit):
            doc_id = f"{namespace}-seed-doc-{q_idx + 1}-{hit_idx + 1}"
            chunk_id = f"{doc_id}-chunk"
            docs_row.append(
                f"Seed evidence for grounded drafting. Query={str(query)[:120]}. "
                f"Reference #{hit_idx + 1} focuses on USAID-style compliance and MEL traceability."
            )
            metas_row.append(
                {
                    "doc_id": doc_id,
                    "chunk_id": chunk_id,
                    "source": f"seed-source-{hit_idx + 1}.pdf",
                    "page": hit_idx + 1,
                    "doc_family": "donor_policy" if hit_idx == 0 else "responsible_ai_guidance",
                }
            )
            ids_row.append(chunk_id)
            distances_row.append(0.05 + (hit_idx * 0.02))
        docs.append(docs_row)
        metadatas.append(metas_row)
        ids.append(ids_row)
        distances.append(distances_row)
    return {"documents": docs, "metadatas": metadatas, "ids": ids, "distances": distances}
