"""Parse email patterns to extract naming conventions."""

from typing import Dict, Any
import re


def parse_email_pattern(value: str) -> Dict[str, Any]:
    """
    Parse email to identify pattern and extract likely name components.

    Examples:
        "john.smith@company.com" -> {"pattern": "first.last", "first": "john", "last": "smith"}
        "jsmith@company.com" -> {"pattern": "firstinitiallast", "first": "j", "last": "smith"}
        "john.smith.jr@company.com" -> {"pattern": "first.last.suffix", "first": "john", "last": "smith"}
    """
    s = (value or "").strip().lower()
    if not s or "@" not in s:
        return {"value": {}, "pattern": None}

    # Split email
    try:
        local_part, domain = s.split("@", 1)
    except ValueError:
        return {"value": {}, "pattern": None}

    if not local_part:
        return {"value": {}, "pattern": None}

    # Remove common prefixes/suffixes and numbers
    cleaned = re.sub(r"\d+$", "", local_part)  # Remove trailing numbers

    # Common patterns to detect
    patterns = []
    likely_first = None
    likely_last = None
    likely_middle = None

    # Split by common delimiters
    if "." in cleaned:
        parts = cleaned.split(".")

        if len(parts) == 2:
            first_part, last_part = parts

            # Check if first part is single initial
            if len(first_part) == 1:
                patterns.append("firstinitial.last")
                likely_first = first_part
                likely_last = last_part
            # Check if last part is single initial
            elif len(last_part) == 1:
                patterns.append("first.lastinitial")
                likely_first = first_part
                likely_last = last_part
            else:
                patterns.append("first.last")
                likely_first = first_part
                likely_last = last_part

        elif len(parts) == 3:
            first_part, middle_part, last_part = parts

            # Check for middle initial
            if len(middle_part) == 1:
                patterns.append("first.middleinitial.last")
                likely_first = first_part
                likely_middle = middle_part
                likely_last = last_part
            # Check for suffix (jr, sr, etc.)
            elif last_part in ["jr", "sr", "ii", "iii", "iv"]:
                patterns.append("first.last.suffix")
                likely_first = first_part
                likely_last = middle_part
            else:
                patterns.append("first.middle.last")
                likely_first = first_part
                likely_middle = middle_part
                likely_last = last_part

        elif len(parts) > 3:
            # Complex pattern
            patterns.append("complex.pattern")
            likely_first = parts[0]
            likely_last = parts[-1]

    elif "_" in cleaned:
        parts = cleaned.split("_")

        if len(parts) == 2:
            patterns.append("first_last")
            likely_first = parts[0]
            likely_last = parts[1]
        else:
            patterns.append("underscore.pattern")
            likely_first = parts[0]
            likely_last = parts[-1]

    elif "-" in cleaned:
        parts = cleaned.split("-")

        if len(parts) == 2:
            # Could be hyphenated last name or first-last
            patterns.append("first-last")
            likely_first = parts[0]
            likely_last = parts[1]
        else:
            patterns.append("hyphen.pattern")
            likely_first = parts[0]
            likely_last = parts[-1]

    else:
        # No delimiter - check for patterns

        # Check if it starts with a single letter followed by a name
        if len(cleaned) > 2 and cleaned[1:].isalpha():
            if cleaned[0].isalpha():
                # Possible first initial + last name (e.g., "jsmith")
                patterns.append("firstinitiallast")
                likely_first = cleaned[0]
                likely_last = cleaned[1:]

        # Check for lastfirst pattern (less common)
        # This would need a name database to detect accurately

        # Default to unknown pattern
        if not patterns:
            patterns.append("username")

    # Build result
    result = {
        "pattern": patterns[0] if patterns else "unknown",
        "likely_first": likely_first,
        "likely_last": likely_last,
        "local_part": local_part,
        "domain": domain,
    }

    if likely_middle:
        result["likely_middle"] = likely_middle

    # Add tokens for additional parsing info
    result["tokens"] = local_part.split(".") if "." in local_part else [local_part]

    # Add confidence based on pattern clarity
    confidence_map = {
        "first.last": 0.95,
        "first_last": 0.95,
        "first-last": 0.90,
        "firstinitial.last": 0.85,
        "first.lastinitial": 0.85,
        "first.middleinitial.last": 0.90,
        "first.middle.last": 0.85,
        "first.last.suffix": 0.80,
        "firstinitiallast": 0.70,
        "username": 0.30,
        "complex.pattern": 0.50,
        "underscore.pattern": 0.60,
        "hyphen.pattern": 0.60,
        "unknown": 0.0,
    }

    result["confidence"] = confidence_map.get(result["pattern"], 0.5)

    return {"value": result}
