import pandas as pd

from fmatch.saas.intelligence.b2b_detectors import (
    B2BFieldDetector,
    auto_map_b2b,
    fingerprint_match,
)
from tests.fixtures.b2b_test_data import (
    SALESFORCE_ACCOUNTS,
    MESSY_CONTACTS
)


def test_detects_obvious_fields():
    detector = B2BFieldDetector(SALESFORCE_ACCOUNTS)
    results = detector.detect_all()

    assert results["account_name"].column == "Account Name"
    assert results["account_name"].confidence >= 0.8
    assert results["domain"].column == "Website"
    assert results["domain"].confidence >= 0.8


def test_handles_messy_headers():
    detector = B2BFieldDetector(MESSY_CONTACTS)
    results = detector.detect_all()

    assert results["account_name"].column == "Organization"
    assert results["account_name"].confidence >= 0.6
    assert results["account_name"].column != "Company_OLD_DO_NOT_USE"


def test_cross_validation_boost():
    df = pd.DataFrame(
        {
            "Company": ["Acme Corp", "Beta LLC", "Gamma Ltd"],
            "Website": ["acme.com", "beta.com", "gamma.com"],
            "Email": ["sales@acme.com", "info@beta.com", "hello@gamma.com"],
        }
    )
    detector = B2BFieldDetector(df)
    results = detector.detect_all()

    assert "cross_validation" in results["domain"].explanation


def test_fingerprint_matching():
    headers = list(SALESFORCE_ACCOUNTS.columns)
    match = fingerprint_match(headers)

    assert match is not None
    assert match[0] == "salesforce_accounts"


def test_requires_confirmation_trigger():
    source_df = pd.DataFrame({"Company": ["Foo Co", "Bar Co", "Baz Co"]})
    reference_df = pd.DataFrame({"Organization": ["Foo Co", "Bar Co", "Baz Co"]})

    result = auto_map_b2b(source_df, reference_df)

    assert result["requires_confirmation"] is True
    assert result["method"] == "detection"