"""
High Risk Handler for Mid Platform.
[AC-IDMP-05, AC-IDMP-20] High-risk scenario detection and mandatory takeover.

High-Risk Scenarios (minimum set):
1. Refund (退款)
2. Complaint Escalation (投诉升级)
3. Privacy/Sensitive Promise (隐私与敏感承诺)
4. Transfer (转人工)
"""

import logging
from dataclasses import dataclass
from typing import Any

from app.models.mid.schemas import (
    ExecutionMode,
    HighRiskScenario,
    PolicyRouterResult,
)

logger = logging.getLogger(__name__)

DEFAULT_HIGH_RISK_SCENARIOS = [
    HighRiskScenario.REFUND,
    HighRiskScenario.COMPLAINT_ESCALATION,
    HighRiskScenario.PRIVACY_SENSITIVE_PROMISE,
    HighRiskScenario.TRANSFER,
]

HIGH_RISK_PATTERNS = {
    HighRiskScenario.REFUND: [
        r"退款",
        r"退货",
        r"退钱",
        r"退费",
        r"还钱",
        r"申请退款",
        r"我要退",
    ],
    HighRiskScenario.COMPLAINT_ESCALATION: [
        r"投诉",
        r"升级投诉",
        r"举报",
        r"12315",
        r"消费者协会",
        r"工商局",
        r"市场监督管理局",
    ],
    HighRiskScenario.PRIVACY_SENSITIVE_PROMISE: [
        r"承诺.{0,10}(退款|赔偿|补偿)",
        r"保证.{0,10}(退款|赔偿|补偿)",
        r"一定.{0,10}(退款|赔偿|补偿)",
        r"肯定能.{0,10}(退款|赔偿|补偿)",
        r"绝对.{0,10}(退款|赔偿|补偿)",
        r"担保",
    ],
    HighRiskScenario.TRANSFER: [
        r"转人工",
        r"人工客服",
        r"人工服务",
        r"真人",
        r"人工",
        r"转接人工",
    ],
}


@dataclass
class HighRiskMatch:
    """High-risk scenario match result."""
    scenario: HighRiskScenario
    matched_pattern: str
    matched_text: str
    confidence: float = 1.0


class HighRiskHandler:
    """
    [AC-IDMP-05, AC-IDMP-20] High-risk scenario handler.
    
    Features:
    - Configurable high-risk scenario set (minimum set required)
    - Pattern-based detection
    - Mandatory takeover to micro_flow or transfer
    """
    
    def __init__(
        self,
        enabled_scenarios: list[HighRiskScenario] | None = None,
        custom_patterns: dict[HighRiskScenario, list[str]] | None = None,
    ):
        self._enabled_scenarios = enabled_scenarios or DEFAULT_HIGH_RISK_SCENARIOS.copy()
        
        if not self._enabled_scenarios:
            raise ValueError("[AC-IDMP-20] High-risk scenario set cannot be empty")
        
        self._patterns = HIGH_RISK_PATTERNS.copy()
        if custom_patterns:
            for scenario, patterns in custom_patterns.items():
                if scenario not in self._patterns:
                    self._patterns[scenario] = []
                self._patterns[scenario].extend(patterns)
        
        self._compiled_patterns = self._compile_patterns()
        
        logger.info(
            f"[AC-IDMP-20] HighRiskHandler initialized with scenarios: "
            f"{[s.value for s in self._enabled_scenarios]}"
        )
    
    def _compile_patterns(self) -> dict[HighRiskScenario, list]:
        """Compile regex patterns for better performance."""
        import re
        compiled = {}
        for scenario in self._enabled_scenarios:
            patterns = self._patterns.get(scenario, [])
            compiled[scenario] = [
                re.compile(p, re.IGNORECASE) for p in patterns
            ]
        return compiled
    
    def detect(self, message: str) -> HighRiskMatch | None:
        """
        [AC-IDMP-05, AC-IDMP-20] Detect high-risk scenario in message.
        
        Args:
            message: User message to check
        
        Returns:
            HighRiskMatch if detected, None otherwise
        """
        for scenario in self._enabled_scenarios:
            patterns = self._compiled_patterns.get(scenario, [])
            for pattern in patterns:
                match = pattern.search(message)
                if match:
                    logger.info(
                        f"[AC-IDMP-05] High-risk scenario detected: "
                        f"scenario={scenario.value}, pattern={pattern.pattern}"
                    )
                    return HighRiskMatch(
                        scenario=scenario,
                        matched_pattern=pattern.pattern,
                        matched_text=match.group(),
                    )
        
        return None
    
    def handle(
        self,
        match: HighRiskMatch,
        context: dict[str, Any] | None = None,
    ) -> PolicyRouterResult:
        """
        [AC-IDMP-05] Handle high-risk scenario by routing to appropriate mode.
        
        Args:
            match: High-risk match result
            context: Additional context (intent match, flow config, etc.)
        
        Returns:
            PolicyRouterResult with execution mode decision
        """
        context = context or {}
        
        if match.scenario == HighRiskScenario.TRANSFER:
            return PolicyRouterResult(
                mode=ExecutionMode.TRANSFER,
                high_risk_triggered=True,
                transfer_message="正在为您转接人工客服，请稍候...",
            )
        
        flow_id = context.get("flow_id")
        if flow_id:
            return PolicyRouterResult(
                mode=ExecutionMode.MICRO_FLOW,
                high_risk_triggered=True,
                target_flow_id=flow_id,
            )
        
        if match.scenario == HighRiskScenario.REFUND:
            return PolicyRouterResult(
                mode=ExecutionMode.MICRO_FLOW,
                high_risk_triggered=True,
                fallback_reason_code="high_risk_refund",
            )
        
        if match.scenario == HighRiskScenario.COMPLAINT_ESCALATION:
            return PolicyRouterResult(
                mode=ExecutionMode.TRANSFER,
                high_risk_triggered=True,
                transfer_message="检测到您可能需要投诉处理，正在为您转接人工客服...",
            )
        
        if match.scenario == HighRiskScenario.PRIVACY_SENSITIVE_PROMISE:
            return PolicyRouterResult(
                mode=ExecutionMode.MICRO_FLOW,
                high_risk_triggered=True,
                fallback_reason_code="high_risk_privacy_promise",
            )
        
        return PolicyRouterResult(
            mode=ExecutionMode.TRANSFER,
            high_risk_triggered=True,
            transfer_message="正在为您转接人工客服...",
        )
    
    def get_enabled_scenarios(self) -> list[HighRiskScenario]:
        """[AC-IDMP-20] Get enabled high-risk scenarios."""
        return self._enabled_scenarios.copy()
    
    def add_scenario(self, scenario: HighRiskScenario) -> None:
        """Add a high-risk scenario to the enabled set."""
        if scenario not in self._enabled_scenarios:
            self._enabled_scenarios.append(scenario)
            if scenario in HIGH_RISK_PATTERNS:
                self._compiled_patterns[scenario] = [
                    __import__('re').compile(p, __import__('re').IGNORECASE)
                    for p in HIGH_RISK_PATTERNS[scenario]
                ]
            logger.info(f"[AC-IDMP-20] Added high-risk scenario: {scenario.value}")
    
    def remove_scenario(self, scenario: HighRiskScenario) -> bool:
        """Remove a high-risk scenario from the enabled set."""
        if scenario in self._enabled_scenarios and len(self._enabled_scenarios) > 1:
            self._enabled_scenarios.remove(scenario)
            if scenario in self._compiled_patterns:
                del self._compiled_patterns[scenario]
            logger.info(f"[AC-IDMP-20] Removed high-risk scenario: {scenario.value}")
            return True
        return False
