"""
Basic smoke tests for remaining operators.

These tests ensure operators don't crash and return expected structure.
Not comprehensive, but catches basic regressions.
"""

import pytest
import sys
import os

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

# Disable external dependencies for smoke tests
os.environ["FM_COMPANY_TO_DOMAIN_REGISTRY"] = "false"
os.environ["FM_COMPANY_TO_DOMAIN_WIKIDATA"] = "false"
os.environ["FM_COMPANY_TO_DOMAIN_DNS"] = "false"
os.environ["FM_COMPANY_TO_DOMAIN_LLM"] = "false"
os.environ["TRANSFORM_ENABLE_LLM_FALLBACK"] = "false"

from fmatch.saas.operators.normalize_company import normalize_company
from fmatch.saas.operators.company_to_domain import company_to_domain
from fmatch.saas.operators.email_domain_match import email_domain_match
from fmatch.saas.operators.extract_domain_root import extract_domain_root
from fmatch.saas.operators.extract_subdomain import extract_subdomain
from fmatch.saas.operators.parse_email_pattern import parse_email_pattern
from fmatch.saas.operators.fix_phone_format import fix_phone_format
from fmatch.saas.operators.normalize_job_function import normalize_job_function
from fmatch.saas.operators.classify_revenue_band import classify_revenue_band
from fmatch.saas.operators.calculate_lead_score import calculate_lead_score
from fmatch.saas.operators.assign_territory import assign_territory
from fmatch.saas.operators.state_name_to_code import state_name_to_code


class TestNormalizeCompany:
    """Basic tests for normalize_company."""

    @pytest.mark.parametrize("input_company,should_clean", [
        ("Acme Corporation", True),
        ("Acme Corp", True),
        ("Acme Inc.", True),
        ("Acme LLC", True),
        ("Acme, Inc.", True),
    ])
    def test_removes_legal_suffixes(self, input_company, should_clean):
        """Test that legal suffixes are removed."""
        result = normalize_company(input_company)
        assert "value" in result
        # Should strip legal suffix
        assert "Corp" not in result["value"] or result["value"] == ""
        assert "Inc" not in result["value"] or result["value"] == ""

    @pytest.mark.parametrize("input_company", [
        "",
        "   ",
        None,
    ])
    def test_empty_input(self, input_company):
        """Test handling of empty inputs."""
        result = normalize_company(input_company)
        assert "value" in result

    def test_returns_dict_structure(self):
        """Test that result has expected structure."""
        result = normalize_company("Test Company Inc")
        assert isinstance(result, dict)
        assert "value" in result
        assert "confidence" in result


class TestCompanyToDomain:
    """Basic tests for company_to_domain."""

    @pytest.mark.parametrize("company,expected_type", [
        ("Google", dict),
        ("Microsoft Corporation", dict),
        ("Amazon.com Inc", dict),
    ])
    def test_returns_dict(self, company, expected_type):
        """Test that operator returns dict."""
        result = company_to_domain(company)
        assert isinstance(result, expected_type)
        assert "value" in result

    @pytest.mark.parametrize("company", [
        "",
        None,
        "   ",
    ])
    def test_empty_input(self, company):
        """Test handling of empty inputs."""
        result = company_to_domain(company)
        assert "value" in result


class TestEmailDomainMatch:
    """Basic tests for email_domain_match."""

    def test_matching_email_and_domain(self):
        """Test when email and domain match."""
        result = email_domain_match({
            "email": "john@acme.com",
            "company": "Acme Corp",
            "domain": "acme.com"
        })
        assert "value" in result
        assert isinstance(result["value"], bool)

    def test_string_input(self):
        """Test with string email input."""
        result = email_domain_match("john@acme.com")
        assert "value" in result
        assert isinstance(result["value"], bool)

    @pytest.mark.parametrize("input_data", [
        {},
        {"email": ""},
        {"email": None},
    ])
    def test_empty_input(self, input_data):
        """Test handling of empty inputs."""
        result = email_domain_match(input_data)
        assert "value" in result


class TestExtractDomainRoot:
    """Basic tests for extract_domain_root."""

    @pytest.mark.parametrize("input_url,has_domain", [
        ("https://www.example.com", True),
        ("example.com", True),
        ("subdomain.example.com", True),
        ("", False),
    ])
    def test_extracts_root(self, input_url, has_domain):
        """Test extraction of domain root."""
        result = extract_domain_root(input_url)
        assert "value" in result
        if has_domain:
            assert result["value"]
        else:
            assert result["value"] == ""


class TestExtractSubdomain:
    """Basic tests for extract_subdomain."""

    @pytest.mark.parametrize("input_url", [
        "https://www.example.com",
        "subdomain.example.com",
        "deep.subdomain.example.com",
        "example.com",
        "",
    ])
    def test_extracts_subdomain(self, input_url):
        """Test subdomain extraction."""
        result = extract_subdomain(input_url)
        assert "value" in result


class TestParseEmailPattern:
    """Basic tests for parse_email_pattern."""

    @pytest.mark.parametrize("email", [
        "first.last@company.com",
        "flast@company.com",
        "firstlast@company.com",
        "first_last@company.com",
        "",
    ])
    def test_parses_pattern(self, email):
        """Test email pattern parsing."""
        result = parse_email_pattern(email)
        assert "value" in result


class TestFixPhoneFormat:
    """Basic tests for fix_phone_format."""

    @pytest.mark.parametrize("phone", [
        "415-555-1234",
        "(415) 555-1234",
        "4155551234",
        "+1 415 555 1234",
        "",
    ])
    def test_formats_phone(self, phone):
        """Test phone formatting."""
        result = fix_phone_format(phone)
        assert "value" in result


class TestNormalizeJobFunction:
    """Basic tests for normalize_job_function."""

    @pytest.mark.parametrize("title", [
        "Software Engineer",
        "Sales Manager",
        "Marketing Director",
        "VP Engineering",
        "",
    ])
    def test_normalizes_function(self, title):
        """Test job function normalization."""
        result = normalize_job_function(title)
        assert "value" in result


class TestClassifyRevenueBand:
    """Basic tests for classify_revenue_band."""

    @pytest.mark.parametrize("revenue,expected_type", [
        (1000000, dict),
        (10000000, dict),
        (100000000, dict),
        (0, dict),
    ])
    def test_classifies_revenue(self, revenue, expected_type):
        """Test revenue band classification."""
        result = classify_revenue_band(revenue)
        assert isinstance(result, expected_type)
        assert "value" in result


class TestCalculateLeadScore:
    """Basic tests for calculate_lead_score."""

    def test_calculates_score(self):
        """Test lead score calculation."""
        data = {
            "email": "john@acme.com",
            "company_size": "100",
            "industry": "Software"
        }
        result = calculate_lead_score(data)
        assert "value" in result

    def test_empty_data(self):
        """Test with empty data."""
        result = calculate_lead_score({})
        assert "value" in result


class TestAssignTerritory:
    """Basic tests for assign_territory."""

    @pytest.mark.parametrize("data", [
        {"country": "US", "state": "CA"},
        {"country": "US", "state": "NY"},
        {"country": "UK"},
        {},
    ])
    def test_assigns_territory(self, data):
        """Test territory assignment."""
        result = assign_territory(data)
        assert "value" in result


class TestStateNameToCode:
    """Basic tests for state_name_to_code."""

    @pytest.mark.parametrize("state,expected_has_code", [
        ("California", True),
        ("New York", True),
        ("Texas", True),
        ("Invalid State", False),
        ("", False),
    ])
    def test_converts_state(self, state, expected_has_code):
        """Test state name to code conversion."""
        result = state_name_to_code(state)
        assert "value" in result


# Enrichment operators - basic smoke tests only
class TestEnrichmentOperators:
    """Smoke tests for enrichment operators that may call external APIs."""

    def test_enrich_company_country(self):
        """Test enrich_company_country doesn't crash."""
        from fmatch.saas.operators.enrich_company_country import enrich_company_country
        result = enrich_company_country({"company": "Test Company", "domain": "test.com"})
        assert "value" in result

    def test_enrich_company_headquarters(self):
        """Test enrich_company_headquarters doesn't crash."""
        from fmatch.saas.operators.enrich_company_headquarters import enrich_company_headquarters
        result = enrich_company_headquarters({"company": "Test Company", "domain": "test.com"})
        assert "value" in result

    def test_enrich_company_industry(self):
        """Test enrich_company_industry doesn't crash."""
        from fmatch.saas.operators.enrich_company_industry import enrich_company_industry
        result = enrich_company_industry({"company": "Test Company", "domain": "test.com"})
        assert "value" in result

    def test_enrich_social_handles(self):
        """Test enrich_social_handles doesn't crash."""
        from fmatch.saas.operators.enrich_social_handles import enrich_social_handles
        result = enrich_social_handles({"company": "Test Company", "domain": "test.com"})
        assert "value" in result

    def test_enrich_stock_info(self):
        """Test enrich_stock_info doesn't crash."""
        from fmatch.saas.operators.enrich_stock_info import enrich_stock_info
        result = enrich_stock_info({"company": "Test Company", "domain": "test.com"})
        assert "value" in result

    def test_enrich_subsidiaries(self):
        """Test enrich_subsidiaries doesn't crash."""
        from fmatch.saas.operators.enrich_subsidiaries import enrich_subsidiaries
        result = enrich_subsidiaries({"company": "Test Company", "domain": "test.com"})
        assert "value" in result


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

    if exit_code == 0:
        print("\n✅ All smoke tests passed!")
    else:
        print(f"\n❌ Smoke tests failed with exit code: {exit_code}")

    return exit_code


if __name__ == "__main__":
    exit(run_tests())
