"""Tests for detect_data_quality_issues operator."""

import os
import sys

import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))

from fmatch.saas.operators.detect_data_quality_issues import (
    detect_data_quality_issues,
)


def _run_row(values, headers):
    return detect_data_quality_issues({"row": values, "headers": headers})


class TestDetectDataQualityIssues:
    """Comprehensive tests for detect_data_quality_issues operator."""

    @pytest.mark.parametrize(
        "email,expected_issue",
        [
            ("test@test.com", "test_data"),
            ("user@company", "invalid_email"),
            ("Placeholder", "placeholder"),
        ],
    )
    def test_email_validation(self, email, expected_issue):
        """Test email validation and placeholder detection."""
        result = _run_row([email], ["Email"])
        has_issue, reason = result["value"]
        assert has_issue is True
        assert reason == expected_issue

    def test_fake_phone_detection(self):
        """Detect fake phone numbers."""
        result = _run_row(["5555551234"], ["Phone"])
        assert result["value"] == [True, "fake_phone"]

    def test_clean_record(self):
        """Clean records should not be flagged."""
        row = ["john@acme.com", "+14155551234", "Acme Corp", "John Smith"]
        headers = ["Email", "Phone", "Company", "Name"]
        result = _run_row(row, headers)
        assert result["value"] == [False, ""]
        assert result["meta"]["checked_cells"] == len(row)

    def test_multiple_issues(self):
        """Multiple issues should be reported in metadata."""
        row = ["test@gmail.com", "5555551234"]
        result = _run_row(row, ["Email", "Phone"])
        has_issue, reason = result["value"]
        assert has_issue is True
        assert reason in {"test_data", "fake_phone"}
        meta = result["meta"]
        assert meta["total_issues"] == 2
        assert set(meta["issue_types"].keys()) == {"test_data", "fake_phone"}

    def test_case_insensitivity(self):
        """Case-insensitive detection for emails."""
        lower = _run_row(["test@gmail.com"], ["Email"])
        upper = _run_row(["TEST@GMAIL.COM"], ["Email"])
        assert lower["value"][0] is True
        assert upper["value"][0] is True
        assert lower["value"][1] == upper["value"][1]

    def test_single_value_payload(self):
        """Single-value payloads should be supported."""
        result = detect_data_quality_issues({"value": "Placeholder"})
        assert result["value"] == [True, "placeholder"]
        assert result["meta"]["issue_type"] == "placeholder"

    def test_header_row(self):
        """Header rows should be ignored."""
        result = detect_data_quality_issues({"is_header": True})
        assert result["value"] == [False, ""]
        assert result["meta"]["reason"] == "header_row"

    def test_international_data(self):
        """International data should not crash or false-positive."""
        row = ["user@münchen.de", "+44 20 7946 0958"]
        result = _run_row(row, ["Email", "Phone"])
        assert isinstance(result["value"], list)
        assert len(result["value"]) == 2
        assert isinstance(result["value"][0], bool)
        assert isinstance(result["value"][1], str)

    def test_metadata_presence(self):
        """Metadata should include checked cell counts."""
        result = _run_row(["test@example.com"], ["Email"])
        assert "meta" in result
        assert result["meta"]["checked_cells"] == 1


def run_tests():
    """Run all tests and report results."""
    exit_code = pytest.main([__file__, "-v", "--tb=short"])

    if exit_code == 0:
        print("\nAll detect_data_quality_issues tests passed!")
    else:
        print(f"\nTests failed with exit code: {exit_code}")

    return exit_code


if __name__ == "__main__":
    raise SystemExit(run_tests())
