from __future__ import annotations

from grantflow.core.strategies.catalog import resolve_donor_record
from grantflow.memory_bank.vector_store import VectorStore

from grantflow.tests.contracts_helpers import fixture_json


def test_donor_resolution_contract_for_key_aliases():
    fixture = fixture_json("donor_resolution_golden.json")
    golden_cases = fixture.get("cases") if isinstance(fixture, dict) else None
    assert isinstance(golden_cases, list) and golden_cases

    for case in golden_cases:
        resolved = resolve_donor_record(case["query"])
        assert resolved is not None
        assert resolved["id"] == case["id"]
        assert resolved["strategy"] == case["strategy"]
        assert resolved["rag_namespace"] == case["rag_namespace"]


def test_vector_store_memory_fallback_contract():
    store = VectorStore()
    store.client = None

    namespace = "Tenant A / USAID ADS 201"
    store.upsert(
        namespace=namespace,
        ids=["doc-1", "doc-2"],
        documents=["Water and sanitation implementation guidance", "Macroeconomic outlook brief"],
        metadatas=[{"source": "guidance.pdf", "chunk_id": "c1"}, {"source": "context.pdf", "chunk_id": "c2"}],
    )

    queried = store.query(namespace=namespace, query_texts="sanitation guidance", top_k=1)
    assert isinstance(queried, list)
    assert queried
    assert "guidance" in queried[0].lower()

    stats = store.get_stats(namespace)
    assert stats["backend"] == "memory"
    assert stats["document_count"] == 2
    assert stats["collection"].startswith("grantflow_tenant_a_usaid_ads_201")
