"""Industry classification and conflict detection."""

import logging
from typing import Optional, Set, Tuple

logger = logging.getLogger(__name__)

# Industry keyword mapping
INDUSTRY_KEYWORDS = {
    "Defense": {
        "missile",
        "missiles",
        "weapons",
        "munitions",
        "radar",
        "aerospace defense",
        "military",
        "defense contractor",
        "armaments",
        "combat",
    },
    "Aerospace": {
        "aerospace",
        "aircraft",
        "spacecraft",
        "satellite",
        "aviation",
        "flight",
        "airborne",
    },
    "Software": {
        "saas",
        "software",
        "email archiving",
        "compliance software",
        "cloud platform",
        "application",
        "apps",
        "digital platform",
    },
    "Retail": {
        "retail",
        "ecommerce",
        "e-commerce",
        "store",
        "consumer goods",
        "shopping",
        "merchandise",
        "storefront",
    },
    "Hospitality": {
        "hotel",
        "accommodation",
        "resort",
        "lodging",
        "inn",
        "motel",
        "hospitality",
    },
    "Transportation": {
        "bus",
        "logistics",
        "freight",
        "transport",
        "trucking",
        "shipping",
        "delivery",
        "courier",
    },
    "Adult": {
        "adult content",
        "porn",
        "xxx",
        "pornography",
        "erotic",
        "taboo porn",
        "adult entertainment",
    },
    "Healthcare": {
        "healthcare",
        "hospital",
        "medical",
        "pharmaceutical",
        "pharma",
        "clinical",
        "health services",
        "patient care",
    },
    "Finance": {
        "banking",
        "financial",
        "finance",
        "investment",
        "insurance",
        "lending",
        "credit",
        "mortgage",
    },
    "Manufacturing": {
        "manufacturing",
        "factory",
        "production",
        "fabrication",
        "assembly",
        "industrial production",
    },
    "Energy": {
        "energy",
        "oil",
        "gas",
        "petroleum",
        "renewable",
        "solar",
        "wind",
        "power generation",
    },
    "Telecommunications": {
        "telecommunications",
        "telecom",
        "wireless",
        "mobile",
        "network",
        "communications",
    },
    "Education": {
        "education",
        "university",
        "school",
        "college",
        "learning",
        "training",
        "academic",
    },
    "Marketing": {
        "marketing",
        "advertising",
        "promotion",
        "branding",
        "ad agency",
        "media buying",
    },
    "Architecture": {
        "architecture",
        "architectural",
        "building design",
        "design firm",
        "construction design",
    },
    "Automotive": {"automotive", "car", "vehicle", "auto", "tire", "automobile"},
}

# Industry conflict matrix - pairs of industries that should never match
CONFLICTING_INDUSTRIES: Set[Tuple[str, str]] = {
    ("Defense", "Software"),
    ("Defense", "Retail"),
    ("Defense", "Hospitality"),
    ("Defense", "Healthcare"),
    ("Defense", "Education"),
    ("Defense", "Marketing"),
    ("Aerospace", "Software"),  # Unless explicitly aerospace software
    ("Aerospace", "Retail"),
    ("Aerospace", "Hospitality"),
    ("Aerospace", "Marketing"),
    ("Adult", "Healthcare"),
    ("Adult", "Education"),
    ("Adult", "Finance"),
    ("Adult", "Defense"),
    ("Manufacturing", "Software"),  # Unless manufacturing software
    ("Healthcare", "Retail"),  # Unless healthcare retail (pharmacies)
    ("Finance", "Manufacturing"),
    ("Architecture", "Software"),  # Unless architecture software
}


def infer_industry(summary: str) -> Optional[str]:
    """
    Infer industry from business description text.

    Strategy:
    1. First check for explicit INDUSTRY: declarations
    2. Fall back to keyword scoring (count matches per industry)
    3. Return industry with most keyword matches

    Args:
        summary: Business description text

    Returns:
        Industry label or None if no match
    """
    if not summary:
        return None

    text = summary.lower()

    # 1. Check for explicit INDUSTRY: declaration first
    # This handles cases where LLM explicitly labeled the industry
    import re

    industry_match = re.search(r"industry:\s*([^\n,;\.]+)", text, re.IGNORECASE)
    if industry_match:
        declared_industry = industry_match.group(1).strip()
        logger.debug(f"Found explicit INDUSTRY declaration: '{declared_industry}'")

        # Map declared industry to our standardized labels
        # Use fuzzy matching to handle variations like "Information Technology" -> "Software"
        declared_lower = declared_industry.lower()

        # Direct mapping for common variations
        if "manufacturing" in declared_lower:
            return "Manufacturing"
        elif (
            "software" in declared_lower
            or "information technology" in declared_lower
            or "technology" in declared_lower
        ):
            # But check if it's REALLY a software company or just uses software
            # If "manufacturing" also appears in the full text, prioritize that
            if "manufacturing" in text or "machinery" in text or "equipment" in text:
                return "Manufacturing"
            return "Software"
        elif "retail" in declared_lower:
            return "Retail"
        elif "healthcare" in declared_lower or "medical" in declared_lower:
            return "Healthcare"
        elif "finance" in declared_lower or "financial" in declared_lower:
            return "Finance"
        elif (
            "transportation" in declared_lower
            or "logistics" in declared_lower
            or "shipping" in declared_lower
        ):
            return "Transportation"
        elif "telecommunication" in declared_lower or "telecom" in declared_lower:
            return "Telecommunications"
        elif "energy" in declared_lower or "utilities" in declared_lower:
            return "Energy"
        elif "defense" in declared_lower or "military" in declared_lower:
            return "Defense"
        elif "aerospace" in declared_lower or "aviation" in declared_lower:
            return "Aerospace"
        elif "education" in declared_lower:
            return "Education"
        elif "hospitality" in declared_lower:
            return "Hospitality"
        elif "marketing" in declared_lower or "advertising" in declared_lower:
            return "Marketing"
        elif "automotive" in declared_lower:
            return "Automotive"
        elif "architecture" in declared_lower:
            return "Architecture"

    # 2. Fall back to keyword scoring
    # Count matches per industry instead of returning first match
    industry_scores = {}

    for label, terms in INDUSTRY_KEYWORDS.items():
        score = sum(1 for term in terms if term in text)
        if score > 0:
            industry_scores[label] = score

    if not industry_scores:
        return None

    # Return industry with highest score
    best_industry = max(industry_scores.items(), key=lambda x: x[1])
    logger.debug(
        f"Industry keyword scores: {industry_scores}, selected: {best_industry[0]}"
    )

    return best_industry[0]


def industries_conflict(industry_a: Optional[str], industry_b: Optional[str]) -> bool:
    """
    Check if two industries are in conflict (should never match).

    Args:
        industry_a: First industry
        industry_b: Second industry

    Returns:
        True if industries conflict, False otherwise
    """
    if not industry_a or not industry_b:
        return False

    # Normalize the pair (order doesn't matter)
    pair = tuple(sorted([industry_a, industry_b]))

    return pair in CONFLICTING_INDUSTRIES


def load_conflict_matrix_from_yaml(path: str) -> Set[Tuple[str, str]]:
    """
    Load conflict matrix from YAML file (optional enhancement).

    Args:
        path: Path to conflicts.yml file

    Returns:
        Set of conflicting industry pairs
    """
    try:
        import yaml
        from pathlib import Path

        p = Path(path)
        if not p.exists():
            logger.info(f"No conflict matrix file at {path}, using default")
            return CONFLICTING_INDUSTRIES

        data = yaml.safe_load(p.read_text()) or {}
        conflicts = set()

        for a, b in data.get("conflicting_industries", []):
            conflicts.add(tuple(sorted([a, b])))

        logger.info(f"Loaded {len(conflicts)} industry conflicts from {path}")
        return conflicts

    except ImportError:
        logger.warning("PyYAML not installed, using default conflict matrix")
        return CONFLICTING_INDUSTRIES
    except Exception as e:
        logger.warning(f"Failed to load conflict matrix from {path}: {e}")
        return CONFLICTING_INDUSTRIES
