"""Normalize industry names to standard categories."""

from typing import Dict, Any
import re
import os
from ..llm_provider import get_llm_provider


# Industry normalization mappings - covers common B2B industries
INDUSTRY_MAPPINGS = {
    # Software & Technology
    "software": [
        "saas",
        "software as a service",
        "b2b software",
        "enterprise software",
        "software development",
        "software company",
        "software vendor",
        "isv",
    ],
    "technology": [
        "tech",
        "high tech",
        "high technology",
        "it",
        "information technology",
        "technology services",
        "tech services",
        "it services",
    ],
    "cloud computing": [
        "cloud",
        "cloud services",
        "cloud infrastructure",
        "iaas",
        "paas",
        "infrastructure as a service",
        "platform as a service",
    ],
    "cybersecurity": [
        "security",
        "cyber security",
        "information security",
        "infosec",
        "network security",
        "data security",
        "security software",
    ],
    "artificial intelligence": [
        "ai",
        "machine learning",
        "ml",
        "deep learning",
        "ai/ml",
        "artificial intelligence/machine learning",
        "data science",
    ],
    # Financial Services
    "financial services": [
        "fintech",
        "financial technology",
        "finance",
        "financial",
        "banking",
        "investment",
        "wealth management",
        "asset management",
    ],
    "insurance": [
        "insurtech",
        "insurance technology",
        "insurance services",
        "reinsurance",
    ],
    "payments": [
        "payment processing",
        "payment services",
        "payment solutions",
        "fintech payments",
    ],
    # Healthcare
    "healthcare": [
        "health care",
        "medical",
        "healthtech",
        "health technology",
        "digital health",
    ],
    "biotechnology": ["biotech", "life sciences", "biopharma", "biopharmaceutical"],
    "pharmaceuticals": [
        "pharma",
        "pharmaceutical",
        "drug development",
        "drug discovery",
    ],
    # E-commerce & Retail
    "e-commerce": [
        "ecommerce",
        "online retail",
        "digital commerce",
        "online marketplace",
    ],
    "retail": ["retail technology", "retail tech", "retailtech", "retail services"],
    # Marketing & Advertising
    "marketing technology": [
        "martech",
        "marketing tech",
        "marketing software",
        "marketing automation",
    ],
    "advertising": [
        "adtech",
        "ad tech",
        "advertising technology",
        "digital advertising",
        "programmatic advertising",
    ],
    # Communications
    "telecommunications": ["telecom", "telco", "communications", "telecom services"],
    # Manufacturing & Industry
    "manufacturing": [
        "industrial",
        "manufacturing technology",
        "industrial technology",
    ],
    "automotive": ["auto", "automobile", "automotive technology", "auto tech"],
    "aerospace": ["aerospace & defense", "aviation", "space technology"],
    # Professional Services
    "consulting": [
        "management consulting",
        "business consulting",
        "consultancy",
        "professional services",
        "advisory services",
    ],
    "legal": ["legal services", "legal tech", "legaltech", "law"],
    # Education
    "education": [
        "edtech",
        "education technology",
        "e-learning",
        "online education",
        "educational services",
        "higher education",
    ],
    # Real Estate
    "real estate": [
        "proptech",
        "property technology",
        "real estate technology",
        "commercial real estate",
        "cre",
    ],
    # Logistics & Transportation
    "logistics": [
        "supply chain",
        "logistics technology",
        "logistics services",
        "transportation",
        "shipping",
        "freight",
    ],
    # Energy
    "energy": [
        "cleantech",
        "clean technology",
        "renewable energy",
        "energy technology",
        "oil & gas",
        "oil and gas",
        "utilities",
    ],
    # Media & Entertainment
    "media": ["media & entertainment", "digital media", "publishing", "broadcasting"],
    "gaming": ["video games", "game development", "gaming technology"],
    # Human Resources
    "human resources": [
        "hr",
        "hr tech",
        "hrtech",
        "human capital management",
        "hcm",
        "recruiting",
        "talent acquisition",
        "staffing",
    ],
    # Food & Beverage
    "food & beverage": [
        "food tech",
        "foodtech",
        "food technology",
        "restaurant technology",
        "food service",
        "hospitality",
    ],
}

# Build reverse mapping for fast lookup
INDUSTRY_LOOKUP = {}
for standard, variations in INDUSTRY_MAPPINGS.items():
    INDUSTRY_LOOKUP[standard.lower()] = standard
    for variation in variations:
        INDUSTRY_LOOKUP[variation.lower()] = standard


def normalize_industry(value: str, *, force_llm: bool = False) -> Dict[str, Any]:
    """
    Normalize industry names to standard categories.

    Examples:
        "SaaS" -> "Software"
        "FinTech" -> "Financial Services"
        "MarTech" -> "Marketing Technology"
    """
    # Handle None/empty
    if value is None or str(value).strip() == "":
        return {"value": None, "confidence": 0.0}

    s = str(value).strip()

    # Clean and lowercase for matching
    cleaned = re.sub(r"[^\w\s&/]", " ", s.lower())
    cleaned = re.sub(r"\s+", " ", cleaned).strip()

    # Direct lookup
    if cleaned in INDUSTRY_LOOKUP:
        return {
            "value": INDUSTRY_LOOKUP[cleaned].title(),
            "original": s,
            "confidence": 1.0,
        }

    # Try fuzzy matching by checking if any key terms are present
    best_match = None
    best_score = 0

    for pattern, standard in INDUSTRY_LOOKUP.items():
        # Check for word boundaries to avoid partial matches
        if len(pattern) > 3:  # Skip very short patterns for fuzzy matching
            pattern_words = set(pattern.split())
            cleaned_words = set(cleaned.split())

            # Calculate overlap
            overlap = len(pattern_words & cleaned_words)
            if overlap > 0:
                score = overlap / len(pattern_words)
                if score > best_score:
                    best_score = score
                    best_match = standard

    if best_match and best_score >= 0.5:
        return {
            "value": best_match.title(),
            "original": s,
            "confidence": round(best_score, 2),
        }

    # Check for compound industries (e.g., "Software and Financial Services")
    found_industries = []
    for word in cleaned.split():
        if word in INDUSTRY_LOOKUP:
            industry = INDUSTRY_LOOKUP[word]
            if industry not in found_industries:
                found_industries.append(industry)

    if found_industries:
        return {
            "value": " & ".join([ind.title() for ind in found_industries[:2]]),  # Max 2
            "original": s,
            "confidence": 0.7,
            "multiple": True,
        }

    # Try AI fallback if enabled and no good match found
    fallback_enabled = (
        os.getenv("TRANSFORM_ENABLE_LLM_FALLBACK", "true").lower() == "true"
    )
    use_llm = force_llm or (best_score < 0.5 and not found_industries)

    if use_llm and fallback_enabled:
        provider = get_llm_provider()
        if provider:
            # Get list of valid industries for the prompt
            valid_industries = list(set(INDUSTRY_MAPPINGS.keys()))[
                :20
            ]  # Top 20 for context
            schema = {
                "type": "object",
                "properties": {
                    "industry": {"type": "string"},
                    "confidence": {"type": "number"},
                },
                "required": ["industry"],
            }
            prompt = (
                f"Categorize this company into one of these standard industries: {', '.join(valid_industries)}.\n"
                f"If it clearly fits multiple, return the primary one.\n"
                f"Return JSON: {{\"industry\":\"<standard category>\", \"confidence\":0.0-1.0}}\n"
                f"Input: \"{value}\""
            )
            try:
                out = provider.generate_json(prompt, schema=schema, num_predict=128)
                result = out.get("value", {}) or {}
                if result.get("industry"):
                    return {
                        "value": result["industry"],
                        "original": s,
                        "confidence": result.get("confidence", 0.7),
                        "method": "ai",
                        "normalized": True,
                    }
            except Exception:
                pass

    # Return original if no match found
    return {"value": s, "original": s, "confidence": 0, "normalized": False}
