import importlib

enrich_company_name_op = importlib.import_module(
    "fmatch.saas.operators.enrich_company_name"
)


def test_enrich_company_name_returns_bq_hit(monkeypatch):
    enrich_company_name_op._LOOKUP_CACHE.clear()
    monkeypatch.setattr(
        enrich_company_name_op,
        "lookup_company_by_domain",
        lambda domain: {
            "label": "Acme Corporation",
            "wikidata_id": "Q123",
            "quality_score": 0.97,
            "source": "foundrygraph_bq",
        },
    )
    monkeypatch.setattr(enrich_company_name_op, "_is_b2c_domain", lambda domain: False)

    result = enrich_company_name_op.enrich_company_name(domain="acme.com")

    assert result["company_name"] == "Acme Corporation"
    assert result["wikidata_id"] == "Q123"
    assert result["source"] == "foundrygraph_bq"
    assert result["confidence"] == 0.95


def test_enrich_company_name_uses_website_when_domain_missing(monkeypatch):
    enrich_company_name_op._LOOKUP_CACHE.clear()
    monkeypatch.setattr(
        enrich_company_name_op,
        "lookup_company_by_domain",
        lambda domain: {"label": "Microsoft Corporation", "source": "foundrygraph_bq"},
    )
    monkeypatch.setattr(enrich_company_name_op, "_is_b2c_domain", lambda domain: False)

    result = enrich_company_name_op.enrich_company_name(
        website="https://www.microsoft.com/path"
    )

    assert result["company_name"] == "Microsoft Corporation"


def test_enrich_company_name_skips_b2c_domains():
    enrich_company_name_op._LOOKUP_CACHE.clear()
    result = enrich_company_name_op.enrich_company_name(domain="gmail.com")
    assert result["company_name"] == ""
    assert result["skipped"] is True
    assert result["skip_reason"] == "b2c_domain"


def test_enrich_company_name_falls_back_to_local_profile(monkeypatch):
    enrich_company_name_op._LOOKUP_CACHE.clear()
    monkeypatch.setattr(enrich_company_name_op, "_lookup_foundrygraph", lambda domain: None)
    monkeypatch.setattr(enrich_company_name_op, "_allow_local_fallback", lambda: True)
    monkeypatch.setattr(
        enrich_company_name_op,
        "_lookup_wikidata_fallback",
        lambda domain: {"name": "Shopify", "wikidata_id": "Q7494", "source": "wikidata_local"},
    )
    monkeypatch.setattr(enrich_company_name_op, "_is_b2c_domain", lambda domain: False)

    result = enrich_company_name_op.enrich_company_name(domain="shopify.com")

    assert result["company_name"] == "Shopify"
    assert result["source"] == "wikidata_local"
    assert result["confidence"] == 0.8


def test_enrich_company_name_caches_successful_results(monkeypatch):
    enrich_company_name_op._LOOKUP_CACHE.clear()
    calls = {"count": 0}

    def fake_lookup(domain):
        calls["count"] += 1
        return {"label": "Acme Corporation", "source": "foundrygraph_bq"}

    monkeypatch.setattr(enrich_company_name_op, "lookup_company_by_domain", fake_lookup)
    monkeypatch.setattr(enrich_company_name_op, "_is_b2c_domain", lambda domain: False)

    first = enrich_company_name_op.enrich_company_name(domain="acme.com")
    second = enrich_company_name_op.enrich_company_name(domain="https://www.acme.com")

    assert first["company_name"] == "Acme Corporation"
    assert second["company_name"] == "Acme Corporation"
    assert calls["count"] == 1


def test_enrich_company_name_falls_back_when_foundrygraph_raises(monkeypatch):
    enrich_company_name_op._LOOKUP_CACHE.clear()
    monkeypatch.setattr(
        enrich_company_name_op,
        "lookup_company_by_domain",
        lambda domain: (_ for _ in ()).throw(RuntimeError("provider down")),
    )
    monkeypatch.setattr(enrich_company_name_op, "_allow_local_fallback", lambda: True)
    monkeypatch.setattr(enrich_company_name_op, "_is_b2c_domain", lambda domain: False)
    monkeypatch.setattr(
        enrich_company_name_op,
        "_lookup_wikidata_fallback",
        lambda domain: {"name": "Fallback Co", "source": "wikidata_local"},
    )

    result = enrich_company_name_op.enrich_company_name(domain="fallback.com")

    assert result["company_name"] == "Fallback Co"
    assert result["source"] == "wikidata_local"


def test_enrich_company_name_transform_handles_batch_lookup_failure(monkeypatch):
    enrich_company_name_op._LOOKUP_CACHE.clear()
    monkeypatch.setattr(
        importlib.import_module("fmatch.saas.services.foundrygraph_bq"),
        "lookup_companies_by_domain",
        lambda domains: (_ for _ in ()).throw(RuntimeError("batch down")),
    )
    monkeypatch.setattr(enrich_company_name_op, "_allow_local_fallback", lambda: True)
    monkeypatch.setattr(enrich_company_name_op, "_is_b2c_domain", lambda domain: False)
    monkeypatch.setattr(
        enrich_company_name_op,
        "_lookup_wikidata_fallback",
        lambda domain: {"name": f"Fallback for {domain}", "source": "wikidata_local"},
    )

    result = enrich_company_name_op.transform(["acme.com", "globex.com"])

    assert result == [["Fallback for acme.com"], ["Fallback for globex.com"]]
