"""Pure job title normalization using heuristics only.

This module provides job title normalization without any external
dependencies - no LLM. It uses only regex patterns and text processing.
"""

from __future__ import annotations

import re
from typing import Optional

from ..heuristics import TITLE_SENIORITY_RULES, TITLE_DEPT_RULES


_WS = re.compile(r"\s+")

# C-level and VP acronyms that should stay uppercase
_UPPERCASE_TITLES = frozenset({
    "VP", "SVP", "EVP",
    "CEO", "CTO", "CFO", "COO", "CMO", "CIO", "CPO", "CSO", "CDO",
})


def _clean_title(s: str) -> str:
    """Clean and normalize whitespace in a title string."""
    t = (s or "").strip()
    # Replace separators with spaces
    t = (
        t.replace("/", " ")
        .replace("-", " ")
        .replace("(", " ")
        .replace(")", " ")
        .replace(",", " ")
    )
    # Collapse multiple spaces
    t = _WS.sub(" ", t)
    return t


def _title_case_core(s: str) -> str:
    """Convert title to proper case, keeping acronyms uppercase."""
    parts = [p for p in s.split(" ") if p]
    out = []
    for p in parts:
        up = p.upper()
        if up in _UPPERCASE_TITLES:
            out.append(up)
        else:
            out.append(p[:1].upper() + p[1:].lower())
    return " ".join(out)


def classify_title_seniority(title: str) -> Optional[str]:
    """Classify job title seniority level.

    Args:
        title: Job title to classify

    Returns:
        Seniority level: "CXO", "VP", "Director", "Manager", "Owner", or None
    """
    cleaned = _clean_title(title)
    for rx, label in TITLE_SENIORITY_RULES:
        if rx.search(cleaned):
            return label
    return None


def classify_title_department(title: str) -> Optional[str]:
    """Classify job title department.

    Args:
        title: Job title to classify

    Returns:
        Department: "Sales", "Marketing", "Engineering", "Finance", "HR",
        "Operations", "IT", "Product", "Customer Success", "Legal", or None
    """
    cleaned = _clean_title(title)
    for rx, dept in TITLE_DEPT_RULES:
        if rx.search(cleaned):
            return dept
    return None


def normalize_title_text(title: str) -> dict:
    """Normalize a job title using pure heuristics.

    This function:
    1. Cleans and normalizes whitespace
    2. Applies proper title casing (preserving acronyms)
    3. Classifies seniority level
    4. Classifies department

    Args:
        title: Job title to normalize

    Returns:
        Dict with keys:
        - title: Normalized title string
        - seniority: Seniority level or "IC" if unclassified
        - department: Department or empty string if unclassified

    Note:
        This function does NOT use LLM fallback.
        For LLM-enhanced normalization, use the saas normalize_title operator.
    """
    raw = _clean_title(title)
    normalized_title = _title_case_core(raw)

    seniority = classify_title_seniority(raw)
    department = classify_title_department(raw)

    return {
        "title": normalized_title or "",
        "seniority": seniority or "IC",
        "department": department or "",
    }
