"""Name pattern detection — shell detection and name cleanup.

Ported from gardener-fork/lib/patterns.py. Handles:
- proper_case_name(): Convert ALL CAPS names to proper case
- is_shell_lead(): Detect shell/holding company names
"""

import re

SHORT_WORDS = {"and", "or", "the", "of", "for", "in", "at", "to", "by",
               "de", "von", "van", "del", "el", "al",
               "llc", "inc", "corp", "pllc", "ltd", "co", "pc", "lp",
               "llp", "lllp", "pa", "plc", "l.l.c", "p.l.l.c"}

ENTITY_SUFFIXES = [
    "LLC", "L.L.C.", "PLLC", "P.L.L.C.", "P.L.L.C",
    "INC", "INC.", "INCORPORATED",
    "CORP", "CORP.", "CORPORATION",
    "PC", "P.C.", "P.C",
    "LP", "L.P.", "LLP", "L.L.P.",
    "LLLP", "L.L.L.P.",
    "CO", "CO.", "COMPANY",
    "LTD", "LTD.", "LIMITED",
    "PA", "P.A.", "P.A",
]

SHELL_PATTERNS_DEFAULT = [
    {"pattern": r"\bholdings\b", "flags": "i"},
    {"pattern": r"\binvestments?\b", "flags": "i"},
    {"pattern": r"\bcapital\b", "flags": "i"},
    {"pattern": r"\bventures?\b", "flags": "i"},
    {"pattern": r"\bproperties\b", "flags": "i"},
    {"pattern": r"\bgroup\b", "flags": "i"},
    {"pattern": r"\bmanagement\b", "flags": "i"},
]


def proper_case_name(name: str) -> str:
    """Convert business name to proper case while preserving entity suffixes.
    
    Examples:
    - "JEFFREY SCHIETZELT PLLC" -> "Jeffrey Schietzelt PLLC"
    - "ALL-STARS SURGICAL ASSIST MA" -> "All-Stars Surgical Assist MA"
    - "Oasis HOME Care LLC" -> "Oasis Home Care LLC"
    """
    if not name:
        return name

    # Main pass: handle >70% uppercase names
    letters = [c for c in name if c.isalpha()]
    if letters:
        uppercase_ratio = sum(1 for c in letters if c.isupper()) / len(letters)
    else:
        uppercase_ratio = 0

    if uppercase_ratio > 0.7:
        words = name.split()
        result_words = []
        for w in words:
            stripped = w.strip(",.()-")
            is_short_acronym = (
                stripped.isupper() and
                stripped.isalpha() and
                2 <= len(stripped) <= 4 and
                not any(c.isdigit() for c in stripped) and
                stripped.lower() not in SHORT_WORDS
            )
            if is_short_acronym:
                result_words.append(w)
            else:
                result_words.append(w.title())
        result = " ".join(result_words)
    else:
        result = name

    # Second pass: title-case individual ALL-CAPS words in mixed-case names
    result = _fix_sporadic_caps(result)
    
    # Preserve entity suffixes
    for suffix in ENTITY_SUFFIXES:
        pattern = re.compile(r'(,?\s*)(' + re.escape(suffix) + r')$', re.I)
        result = pattern.sub(lambda m: m.group(1) + suffix.upper(), result)

    # Fix common words
    result = re.sub(r'\bAnd\b', 'and', result)
    result = re.sub(r'\bOf\b', 'of', result)
    result = re.sub(r'\bThe\b', 'the', result)
    result = re.sub(r'\bFor\b', 'for', result)

    # Handle Mc/Mac prefixes
    result = re.sub(r"\bMc([a-z])", lambda m: "Mc" + m.group(1).upper(), result)
    result = re.sub(r"\bMac([aeiou])", lambda m: "Mac" + m.group(1).upper(), result, flags=re.I)
    result = re.sub(r"\bDe\s+([A-Z])", lambda m: "De " + m.group(1), result)
    result = re.sub(r"\bVon\s+([A-Z])", lambda m: "von " + m.group(1), result)
    result = re.sub(r"\bVan\s+([A-Z])", lambda m: "van " + m.group(1), result)

    return result


def _fix_sporadic_caps(name: str) -> str:
    """Fix sporadic ALL-CAPS words in mixed-case names."""
    words = name.split()
    result_words = []
    for w in words:
        if w.isupper() and w.isalpha() and len(w) > 1 and w.lower() not in SHORT_WORDS:
            result_words.append(w.title())
        else:
            result_words.append(w)
    return " ".join(result_words)


def is_shell_lead(name: str, shell_patterns: list = None) -> bool:
    """Check if business name matches shell/holding company patterns.
    
    Args:
        name: Business name
        shell_patterns: List of pattern dicts with 'pattern' and 'flags' keys.
                       If None, uses default patterns.
    
    Returns:
        True if name matches shell patterns
    """
    if not name:
        return False
    
    if shell_patterns is None:
        shell_patterns = SHELL_PATTERNS_DEFAULT
    
    for p in shell_patterns:
        pattern = p["pattern"]
        flags = re.I if "i" in p.get("flags", "") else 0
        if re.search(pattern, name, flags):
            return True
    
    return False