"""
Intent Detection Module

Keyword-based intent classification for ERP/CRM domain.
"""

from typing import Optional

# Intent normalization map (raw LLM intent → display group)
# Used by both main code and dashboard for consistent grouping
INTENT_MAP: dict[str, str] = {
    # ERP
    "erp_inquiry": "ERP",
    "erp_cloud": "ERP",
    "erp_demo": "ERP",
    "erp_on premise": "ERP",
    "erp_features": "ERP",
    "traffic_erp": "ERP",

    # CRM
    "crm_inquiry": "CRM",
    "crm_features": "CRM",
    "crm_leads": "CRM",

    # Pricing
    "pricing": "Pricing",
    "pricing_inquiry": "Pricing",

    # Scheduling
    "schedule_call": "Scheduling",
    "date_request": "Scheduling",

    # Closing
    "closing": "Closing",
    "goodbye": "Closing",
    "farewell": "Closing",
    "thank_you": "Closing",

    # Introduction
    "introduction": "Introduction",
    "greeting": "Introduction",
    "initial": "Introduction",

    # Clarification
    "clarification": "Clarification",
    "clarification_needed": "Clarification",
    "needs_clarification": "Clarification",

    # General / info
    "general": "General",
    "general_request": "General",
    "general_discussion": "General",
    "general_concern": "General",
    "general_inquiry": "General",
    "info_request": "General",
    "service_information": "General",
    "feature_details": "General",
    "data_package_info": "General",
    "implementation_details": "General",
    "software_name": "General",
    "solution_power": "General",
    "implementation": "General",
    "demo_request": "General",

    # Escalation
    "contact": "Escalation",
    "contact_agent": "Escalation",
    "human_agent": "Escalation",

    # Technical issues (from original)
    "connectivity_issue": "Technical",
    "account_access_issue": "Technical",
    "system_issue": "Technical",

    # Explicit unknowns
    "none": "Unknown",
    "unknown": "Unknown",
}

# Group colors for dashboard visualization
GROUP_COLORS: dict[str, str] = {
    "ERP": "#6366f1",
    "CRM": "#8b5cf6",
    "Pricing": "#f59e0b",
    "Scheduling": "#10b981",
    "Closing": "#ec4899",
    "Introduction": "#3b82f6",
    "Clarification": "#f97316",
    "General": "#64748b",
    "Escalation": "#ef4444",
    "Technical": "#06b6d4",
    "Other": "#a3a3a3",
    "Unknown": "#475569",
}


def normalize_intent(raw: str) -> str:
    """
    Normalize raw LLM intent to display group.

    Args:
        raw: Raw intent string from LLM

    Returns:
        Normalized group name (e.g., "ERP", "CRM", "Unknown")
    """
    if not raw or not raw.strip():
        return "Unknown"
    return INTENT_MAP.get(raw.strip().lower(), "Other")


def guess_intent(text: str) -> str:
    """
    Guess intent from user utterance using keyword matching.

    This provides a fallback when LLM is unavailable.

    Args:
        text: User utterance text

    Returns:
        Guessed intent string
    """
    t = (text or "").lower()

    # Check for goodbye/closing FIRST (terminal intent)
    if any(k in t for k in ["bye", "goodbye", "good bye", "see you", "talk later", "gotta go", "have to go", "that's it"]):
        return "closing"

    # Thank you (often signals closing)
    if any(k in t for k in ["thank"]):
        return "closing"

    # ERP/CRM specific intents
    if any(k in t for k in ["erp", "enterprise resource"]):
        return "erp_inquiry"

    if any(k in t for k in ["crm", "customer relationship"]):
        return "crm_inquiry"

    if any(k in t for k in ["lead", "opportunity", "pipeline", "conversion", "prospect"]):
        return "crm_features"

    if any(k in t for k in ["price", "pricing", "cost", "how much", "subscription", "plan"]):
        return "pricing_inquiry"

    if any(k in t for k in ["implementation", "deploy", "setup", "install", "integrate"]):
        return "implementation"

    if any(k in t for k in ["demo", "trial", "test", "show me"]):
        return "demo_request"

    # Technical support intents
    if any(k in t for k in ["wifi", "wi-fi", "internet", "slow", "speed", "connection"]):
        return "connectivity_issue"

    if any(k in t for k in ["portal", "login", "account", "password", "cannot access"]):
        return "account_access_issue"

    if any(k in t for k in ["server", "system", "down", "error", "not loading"]):
        return "system_issue"

    # Introduction/greeting
    if any(k in t for k in ["name is", "calling", "hello", "hi"]):
        return "introduction"

    return "unknown"


def is_terminal_intent(intent: str) -> bool:
    """
    Check if intent signals end of conversation.

    Args:
        intent: Intent string

    Returns:
        True if intent is terminal (closing, escalation)
    """
    return intent in ("closing", "goodbye", "farewell", "thank_you")


def get_intent_color(intent: str) -> str:
    """
    Get color for intent visualization.

    Args:
        intent: Intent string (raw or normalized)

    Returns:
        Hex color code
    """
    normalized = normalize_intent(intent)
    return GROUP_COLORS.get(normalized, GROUP_COLORS["Other"])
