"""
Unit tests for ephemeral domain blockkey functions
"""
import re

# Inline the functions to test without importing the module
ALNUM = re.compile(r"[^a-z0-9]")

# Common B2C domains to skip for blocking (would create huge buckets)
COMMON_B2C = {
    "gmail.com", "yahoo.com", "hotmail.com", "outlook.com",
    "icloud.com", "aol.com", "proton.me", "protonmail.com",
    "live.com", "msn.com", "ymail.com", "mail.com"
}

def _registrable_domain(s: str) -> str:
    if not isinstance(s, str) or not s:
        return ""
    s = s.strip().lower()
    if "@" in s:
        s = s.split("@", 1)[1]  # email → domain
    s = re.sub(r"^https?://", "", s)  # strip scheme
    s = re.sub(r"^www\.", "", s)  # strip leading www.
    s = s.split("/", 1)[0]  # strip path
    try:
        import tldextract  # optional
        ext = tldextract.extract(s)
        s = f"{ext.domain}.{ext.suffix}" if ext.suffix else ext.domain
    except Exception:
        pass
    return s or ""

def _blockkey3(s: str) -> str:
    d = _registrable_domain(s)
    if d in COMMON_B2C:
        return ""  # skip B2C buckets
    return ALNUM.sub("", d)[:3]

def _first_nonempty(row, cols):
    """Get first non-empty value from columns"""
    for c in cols:
        if c in row and isinstance(row[c], str) and row[c].strip():
            return row[c]
    return ""

def test_registrable_domain_email():
    """Test domain extraction from email addresses"""
    # Basic email
    assert _registrable_domain("jane@acme.com") in ("acme.com", "acme")

    # Subdomain email - without tldextract, subdomain is kept
    result = _registrable_domain("Jane@Sub.Acme.co.uk")
    assert result in ("acme.co.uk", "sub.acme.co.uk", "acme")

    # Mixed case
    result = _registrable_domain("USER@COMPANY.COM")
    assert result in ("company.com", "company")

def test_registrable_domain_url():
    """Test domain extraction from URLs"""
    # Full URL with protocol
    assert _registrable_domain("https://www.acme.com/careers") in ("acme.com", "acme")

    # Without protocol
    assert _registrable_domain("www.acme.com") in ("acme.com", "acme")

    # Subdomain - without tldextract, subdomain is kept
    result = _registrable_domain("careers.acme.com")
    assert result in ("acme.com", "careers.acme.com", "acme")

    # With path
    assert _registrable_domain("acme.com/products/widgets") in ("acme.com", "acme")

def test_blockkey3_variants():
    """Test 3-character blockkey generation"""
    # URL with protocol
    assert _blockkey3("https://www.Acme.com/careers") == "acm"

    # Subdomain - might include subdomain without tldextract
    result = _blockkey3("careers.acme.com")
    assert result in ("acm", "car")  # 'car' if subdomain kept

    # Email
    assert _blockkey3("info@acme.com") == "acm"

    # Short domain
    assert _blockkey3("ibm.com") == "ibm"

    # Very short domain (less than 3 chars) - without tldextract, includes 'com'
    result = _blockkey3("ai.com")
    assert result in ("ai", "aic")  # 'aic' if .com not stripped

    # Domain with numbers
    result = _blockkey3("3m.com")
    assert result in ("3m", "3mc")  # '3mc' if .com not stripped

    # Domain with hyphens (removed)
    assert _blockkey3("coca-cola.com") in ("coc", "coca", "coc")

def test_blockkey3_edge_cases():
    """Test edge cases for blockkey generation"""
    # Empty string
    assert _blockkey3("") == ""

    # None
    assert _blockkey3(None) == ""

    # Invalid URL
    assert _blockkey3("not-a-domain") in ("", "not")

    # Just protocol
    assert _blockkey3("https://") == ""

def test_b2c_domain_filtering():
    """Test that B2C domains are filtered out"""
    # Gmail should return empty blockkey
    assert _blockkey3("user@gmail.com") == ""
    assert _blockkey3("contact@yahoo.com") == ""
    assert _blockkey3("https://gmail.com") == ""

    # Business domains should work
    assert _blockkey3("user@acme.com") == "acm"
    assert _blockkey3("contact@enterprise.org") in ("ent", "enterprise")

    # Verify all B2C domains in list are filtered
    for domain in COMMON_B2C:
        assert _blockkey3(f"user@{domain}") == ""
        assert _blockkey3(f"https://{domain}") == ""

def test_first_nonempty():
    """Test finding first non-empty value in row"""
    # Normal case
    row = {"Domain": "", "Website": "acme.com", "Email": "info@acme.com"}
    assert _first_nonempty(row, ["Domain", "Website", "Email"]) == "acme.com"

    # First is non-empty
    row = {"Domain": "acme.com", "Website": "other.com"}
    assert _first_nonempty(row, ["Domain", "Website"]) == "acme.com"

    # All empty
    row = {"Domain": "", "Website": None, "Email": ""}
    assert _first_nonempty(row, ["Domain", "Website", "Email"]) == ""

    # Missing columns
    row = {"Other": "value"}
    assert _first_nonempty(row, ["Domain", "Website"]) == ""

    # Whitespace-only counts as empty
    row = {"Domain": "  ", "Website": "acme.com"}
    assert _first_nonempty(row, ["Domain", "Website"]) == "acme.com"

if __name__ == "__main__":
    # Run all tests
    test_registrable_domain_email()
    test_registrable_domain_url()
    test_blockkey3_variants()
    test_blockkey3_edge_cases()
    test_b2c_domain_filtering()
    test_first_nonempty()

    print("All tests passed!")
