from __future__ import annotations

from fastapi.testclient import TestClient

from fmatch.saas.main import create_app


def _sample_payload() -> dict:
    return {
        "mode": "match",
        "source_schema": {
            "row_count": 5000,
            "columns": [
                {
                    "name": "Source Record ID",
                    "samples": ["001Kb00001IgDgHIAV", "001Kb00001IgD9LIAV"],
                    "data_type": "id",
                },
                {"name": "Email", "samples": ["a@example.com"], "data_type": "email"},
                {"name": "Company", "samples": ["Acme"], "data_type": "string"},
                {"name": "State", "samples": ["CA"], "data_type": "string"},
            ]
        },
        "reference_schema": {
            "row_count": 20000,
            "columns": [
                {
                    "name": "Primary Email",
                    "samples": ["b@example.com"],
                    "data_type": "email",
                },
                {"name": "Account Name", "samples": ["Acme"], "data_type": "string"},
                {"name": "Lead State", "samples": ["CA"], "data_type": "string"},
                {
                    "name": "Lead ID",
                    "samples": ["00QUl000007vFhS", "00QUl00000DeYCd"],
                    "data_type": "id",
                },
            ]
        },
    }


def test_ai_match_config_falls_back_when_provider_missing(monkeypatch):
    import fmatch.saas.api.v2.ai_match_config as ai_module

    monkeypatch.setattr(ai_module, "get_llm_provider", lambda: None)
    client = TestClient(create_app())

    resp = client.post("/api/v2/ai/match-config", json=_sample_payload())
    assert resp.status_code == 200
    data = resp.json()

    assert isinstance(data["mappings"], list) and len(data["mappings"]) >= 1
    joined_warnings = " ".join(data.get("warnings", []))
    assert "heuristic" in joined_warnings.lower()
    assert data["reasoning"]

    hints = data.get("option_hints") or {}
    assert hints.get("block") == "domain"
    assert hints.get("anchor") in (None, "State", "Country")
    assert hints.get("source_id") == "Source Record ID"
    assert hints.get("reference_id") == "Lead ID"



def test_ai_match_config_falls_back_when_provider_errors(monkeypatch):
    import fmatch.saas.api.v2.ai_match_config as ai_module

    class ExplodingProvider:
        def generate_json(self, *_, **__):
            raise RuntimeError("vertex down")

    monkeypatch.setattr(ai_module, "get_llm_provider", lambda: ExplodingProvider())
    client = TestClient(create_app())

    resp = client.post("/api/v2/ai/match-config", json=_sample_payload())
    assert resp.status_code == 200
    data = resp.json()

    assert isinstance(data["mappings"], list) and len(data["mappings"]) >= 1
    joined_warnings = " ".join(data.get("warnings", []))
    assert "temporarily unavailable" in joined_warnings.lower()
    assert data["reasoning"]

    hints = data.get("option_hints") or {}
    assert hints.get("block") in ("domain", "state")
    assert hints.get("source_id") == "Source Record ID"
