import pandas as pd
import pytest

from fmatch.saas.services.match_gateway import MatchConfig, MatchGateway


class _DummyResult:
    def __init__(self, matches: pd.DataFrame):
        self.matches = matches


def test_normalize_result_scales_scores_and_ids() -> None:
    gateway = MatchGateway()
    config = MatchConfig(
        mappings=[],
        threshold=0.8,
        source_id_column="__source_id",
        reference_id_column="__reference_id",
    )
    raw = pd.DataFrame(
        {
            "__source_id": [1],
            "__reference_id": [7],
            "match_score": [85],
        }
    )

    result = gateway._normalize_result(_DummyResult(raw), config)

    assert result.matches["score"].iloc[0] == 0.85
    assert result.matches["source_id"].iloc[0] == 1
    assert result.matches["reference_id"].iloc[0] == 7
    assert result.stats["above_threshold"] == 1


def test_resolve_blocking_domain_priority() -> None:
    gateway = MatchGateway()
    source_df = pd.DataFrame({"Website": ["acme.com"], "Name": ["Acme"]})
    ref_df = pd.DataFrame({"Domain": ["acme.com"], "Account": ["Acme"]})

    blocking = gateway._resolve_blocking({}, source_df, ref_df, None, None, [])

    assert blocking == {
        "source_column": "Website",
        "reference_column": "Domain",
        "key_length": 3,
    }


@pytest.mark.asyncio
async def test_resolve_config_with_mappings_uses_cli_blocking() -> None:
    gateway = MatchGateway()
    source_df = pd.DataFrame({"Name": ["Acme"]})
    ref_df = pd.DataFrame({"Account": ["Acme"]})
    mappings = [{"source": "Name", "reference": "Account", "weight": 1.0}]

    config = await gateway._resolve_config(
        source_df,
        ref_df,
        source_col="Name",
        target_col="Account",
        threshold=0.82,
        mappings=mappings,
    )

    assert config.threshold == 0.82
    assert config.blocking_strategy == {
        "source_column": "Name",
        "reference_column": "Account",
        "key_length": 3,
    }


@pytest.mark.asyncio
async def test_match_direct_passes_options_to_engine() -> None:
    gateway = MatchGateway()
    source_df = pd.DataFrame({"Name": ["Acme"], "__source_id": ["s1"]})
    ref_df = pd.DataFrame({"Account": ["Acme"], "__reference_id": ["r1"]})
    config = MatchConfig(
        mappings=[{"source": "Name", "reference": "Account", "weight": 1.0}],
        threshold=0.8,
        source_id_column="__source_id",
        reference_id_column="__reference_id",
    )
    captured = {}

    class _DummyEngine:
        async def match_records(self, *_args, **kwargs):
            captured.update(kwargs)
            return _DummyResult(pd.DataFrame())

    await gateway._match_direct(
        _DummyEngine(),
        source_df,
        ref_df,
        config,
        options={"use_row_candidates": False},
    )

    assert captured["options"] == {"use_row_candidates": False}
