# grantflow/tests/test_integration_presets.py

from fastapi.testclient import TestClient

from grantflow.api.app import app

client = TestClient(app)


def test_list_donors():
    response = client.get("/donors")
    assert response.status_code == 200
    donors = response.json()["donors"]
    donor_ids = [d["id"] for d in donors]
    assert "usaid" in donor_ids
    assert "eu" in donor_ids
    assert "worldbank" in donor_ids


def test_get_demo_presets_bundle():
    response = client.get("/demo/presets")
    assert response.status_code == 200
    body = response.json()
    generate_presets = body.get("generate_presets")
    ingest_presets = body.get("ingest_presets")
    assert isinstance(generate_presets, list) and generate_presets
    assert isinstance(ingest_presets, list) and ingest_presets
    generate_keys = {str(item.get("preset_key") or "") for item in generate_presets if isinstance(item, dict)}
    assert "usaid_gov_ai_kazakhstan" in generate_keys
    assert "rbm-usaid-ai-civil-service-kazakhstan" in generate_keys
    ingest_keys = {str(item.get("preset_key") or "") for item in ingest_presets if isinstance(item, dict)}
    assert "usaid_gov_ai_kazakhstan" in ingest_keys
    sample_generate = next(
        item
        for item in generate_presets
        if isinstance(item, dict) and item.get("preset_key") == "usaid_gov_ai_kazakhstan"
    )
    assert isinstance(sample_generate.get("generate_payload"), dict)
    assert isinstance(str(sample_generate.get("label") or ""), str)
    sample_ingest = next(
        item
        for item in ingest_presets
        if isinstance(item, dict) and item.get("preset_key") == "usaid_gov_ai_kazakhstan"
    )
    assert isinstance(sample_ingest.get("metadata"), dict)
    assert isinstance(sample_ingest.get("checklist_items"), list)


def test_list_generate_presets():
    response = client.get("/generate/presets")
    assert response.status_code == 200
    body = response.json()
    presets = body.get("presets")
    assert isinstance(presets, list) and presets
    preset_keys = {str(item.get("preset_key") or "") for item in presets if isinstance(item, dict)}
    assert "usaid_gov_ai_kazakhstan" in preset_keys
    assert "rbm-usaid-ai-civil-service-kazakhstan" in preset_keys
    legacy_row = next(
        item for item in presets if isinstance(item, dict) and item.get("preset_key") == "usaid_gov_ai_kazakhstan"
    )
    assert legacy_row.get("source_kind") == "legacy"
    assert isinstance(legacy_row.get("generate_payload"), dict)
    rbm_row = next(
        item
        for item in presets
        if isinstance(item, dict) and item.get("preset_key") == "rbm-usaid-ai-civil-service-kazakhstan"
    )
    assert rbm_row.get("source_kind") == "rbm"
    assert isinstance(rbm_row.get("generate_payload"), dict)


def test_get_generate_preset_unified_detail_supports_runtime_flags():
    response = client.get(
        "/generate/presets/rbm-usaid-ai-civil-service-kazakhstan",
        params={
            "llm_mode": "false",
            "hitl_enabled": "false",
            "architect_rag_enabled": "false",
            "strict_preflight": "true",
        },
    )
    assert response.status_code == 200
    body = response.json()
    assert body["preset_key"] == "rbm-usaid-ai-civil-service-kazakhstan"
    assert body["source_kind"] == "rbm"
    payload = body.get("generate_payload")
    assert isinstance(payload, dict)
    assert payload.get("llm_mode") is False
    assert payload.get("hitl_enabled") is False
    assert payload.get("architect_rag_enabled") is False
    assert payload.get("strict_preflight") is True


def test_get_generate_preset_unified_detail_unknown_returns_404():
    response = client.get("/generate/presets/not-a-real-preset-key")
    assert response.status_code == 404
    detail = response.json().get("detail") or {}
    assert detail.get("reason") == "generate_preset_not_found"
    assert detail.get("preset_key") == "not-a-real-preset-key"
    assert isinstance(detail.get("available"), list)


def test_list_ingest_presets():
    response = client.get("/ingest/presets")
    assert response.status_code == 200
    body = response.json()
    presets = body.get("presets")
    assert isinstance(presets, list) and presets
    preset_keys = {str(item.get("preset_key") or "") for item in presets if isinstance(item, dict)}
    assert "usaid_gov_ai_kazakhstan" in preset_keys
    assert "eu_digital_governance_moldova" in preset_keys
    assert "worldbank_public_sector_uzbekistan" in preset_keys


def test_get_ingest_preset():
    response = client.get("/ingest/presets/usaid_gov_ai_kazakhstan")
    assert response.status_code == 200
    body = response.json()
    assert body["preset_key"] == "usaid_gov_ai_kazakhstan"
    assert body["donor_id"] == "usaid"
    metadata = body.get("metadata")
    assert isinstance(metadata, dict)
    assert metadata.get("doc_family") == "donor_policy"
    checklist_items = body.get("checklist_items")
    assert isinstance(checklist_items, list) and checklist_items
    assert any(str(item.get("id") or "") == "country_context" for item in checklist_items if isinstance(item, dict))
    recommended_docs = body.get("recommended_docs")
    assert isinstance(recommended_docs, list) and recommended_docs


def test_get_ingest_preset_unknown_returns_404():
    response = client.get("/ingest/presets/not-a-real-preset")
    assert response.status_code == 404
    assert "Unknown preset_key" in str(response.json().get("detail") or "")


def test_list_generate_legacy_presets():
    response = client.get("/generate/presets/legacy")
    assert response.status_code == 200
    body = response.json()
    presets = body.get("presets")
    assert isinstance(presets, list) and presets
    preset_keys = {str(item.get("preset_key") or "") for item in presets if isinstance(item, dict)}
    assert "usaid_gov_ai_kazakhstan" in preset_keys
    assert "eu_digital_governance_moldova" in preset_keys
    assert "worldbank_public_sector_uzbekistan" in preset_keys


def test_get_generate_legacy_preset():
    response = client.get("/generate/presets/legacy/usaid_gov_ai_kazakhstan")
    assert response.status_code == 200
    body = response.json()
    assert body["preset_key"] == "usaid_gov_ai_kazakhstan"
    assert body["donor_id"] == "usaid"
    generate_payload = body.get("generate_payload")
    assert isinstance(generate_payload, dict)
    assert generate_payload.get("donor_id") == "usaid"
    assert generate_payload.get("llm_mode") is True
    assert generate_payload.get("hitl_enabled") is True
    input_context = generate_payload.get("input_context")
    assert isinstance(input_context, dict)
    assert str(input_context.get("country") or "").strip().lower() == "kazakhstan"


def test_get_generate_legacy_preset_unknown_returns_404():
    response = client.get("/generate/presets/legacy/not-a-real-preset")
    assert response.status_code == 404
    assert "Unknown preset_key" in str(response.json().get("detail") or "")


def test_list_rbm_generate_presets():
    response = client.get("/generate/presets/rbm")
    assert response.status_code == 200
    body = response.json()
    presets = body.get("presets")
    assert isinstance(presets, list) and presets
    sample_ids = {str(item.get("sample_id") or "") for item in presets if isinstance(item, dict)}
    assert "rbm-usaid-ai-civil-service-kazakhstan" in sample_ids
    assert "rbm-eu-youth-employment-jordan" in sample_ids


def test_get_rbm_generate_preset_with_runtime_flags():
    response = client.get(
        "/generate/presets/rbm/rbm-eu-youth-employment-jordan",
        params={
            "llm_mode": "true",
            "hitl_enabled": "true",
            "architect_rag_enabled": "true",
            "strict_preflight": "true",
        },
    )
    assert response.status_code == 200
    body = response.json()
    assert body["sample_id"] == "rbm-eu-youth-employment-jordan"
    assert isinstance(body.get("payload"), dict)
    generate_payload = body.get("generate_payload")
    assert isinstance(generate_payload, dict)
    assert generate_payload.get("donor_id") == "eu"
    assert generate_payload.get("llm_mode") is True
    assert generate_payload.get("hitl_enabled") is True
    assert generate_payload.get("architect_rag_enabled") is True
    assert generate_payload.get("strict_preflight") is True
    input_context = generate_payload.get("input_context")
    assert isinstance(input_context, dict)
    assert str(input_context.get("project") or "").strip() != ""
    assert str(input_context.get("country") or "").strip().lower() == "jordan"


def test_get_rbm_generate_preset_unknown_sample_returns_404():
    response = client.get("/generate/presets/rbm/unknown-sample-id")
    assert response.status_code == 404
    assert "Unknown sample_id" in str(response.json().get("detail") or "")
