"""智能航空公司识别模块

自动从推文文本中识别涉及的航空公司，提供更智能的分析体验。
"""

import re
from typing import Optional, List, Dict


class AirlineDetector:
    """航空公司识别器"""
    
    def __init__(self):
        # 航空公司名称映射（包含常见变体）
        self.airline_patterns = {
            "United": [
                r"@[Uu]nited", r"@[Uu]nitedAir", r"united airlines?", 
                r"united air", r"#united"
            ],
            "Delta": [
                r"@[Dd]elta", r"@[Dd]eltaAir", r"delta airlines?", 
                r"delta air", r"#delta"
            ],
            "American": [
                r"@[Aa]merican", r"@[Aa]mericanAir", r"american airlines?", 
                r"american air", r"#american"
            ],
            "Southwest": [
                r"@[Ss]outhwest", r"@[Ss]outhwestAir", r"southwest airlines?", 
                r"southwest air", r"#southwest"
            ],
            "US Airways": [
                r"@[Uu][Ss][Aa]irways", r"us airways", r"usairways", 
                r"#usairways"
            ],
            "JetBlue": [
                r"@[Jj]etblue", r"@[Jj]etblueair", r"jetblue airlines?", 
                r"jetblue air", r"#jetblue"
            ],
            "Virgin America": [
                r"@[Vv]irginamerica", r"virgin america", r"virginamerica", 
                r"#virginamerica"
            ]
        }
    
    def detect_airlines(self, text: str) -> List[str]:
        """检测推文中提到的所有航空公司"""
        
        detected_airlines = []
        
        for airline, patterns in self.airline_patterns.items():
            for pattern in patterns:
                if re.search(pattern, text, re.IGNORECASE):
                    if airline not in detected_airlines:
                        detected_airlines.append(airline)
                    break  # 找到一个匹配就继续下一个航空公司
        
        return detected_airlines
    
    def get_primary_airline(self, text: str) -> Optional[str]:
        """获取主要的航空公司（基于出现频率和位置）"""
        
        airlines = self.detect_airlines(text)
        
        if not airlines:
            return None
        
        # 简单的优先级策略
        # 1. 出现在开头的航空公司优先
        text_lower = text.lower()
        for airline in airlines:
            airline_lower = airline.lower()
            if text_lower.startswith(f"@{airline_lower}") or \
               text_lower.startswith(airline_lower):
                return airline
        
        # 2. 返回第一个检测到的航空公司
        return airlines[0]
    
    def analyze_airline_context(self, text: str) -> Dict:
        """分析航空公司的上下文信息"""
        
        airlines = self.detect_airlines(text)
        
        return {
            "detected_airlines": airlines,
            "airline_count": len(airlines),
            "primary_airline": self.get_primary_airline(text) if airlines else None,
            "is_multiple_airlines": len(airlines) > 1,
            "has_airline_mention": len(airlines) > 0
        }


def extract_airline_context(text: str) -> Dict:
    """提取航空公司上下文信息的便捷函数"""
    detector = AirlineDetector()
    return detector.analyze_airline_context(text)


def get_suggested_airline(text: str) -> str:
    """获取建议的航空公司（用于兼容现有接口）"""
    detector = AirlineDetector()
    primary_airline = detector.get_primary_airline(text)
    
    if primary_airline:
        return primary_airline
    else:
        # 如果没有检测到航空公司，使用默认值或根据内容推断
        return "通用航空公司"  # 或根据其他上下文推断