import re
from typing import List


class DataTypeDetector:
    """数据类型检测和解析"""
    
    @staticmethod
    def is_numeric(text: str) -> bool:
        """判断文本是否为数字（15位以内的数值）"""
        if not text:
            return False
        
        clean_text = re.sub(r'[,，\s-]', '', text)
        
        if len(clean_text) > 15:
            return False
        
        try:
            float(clean_text)
            return True
        except ValueError:
            return False
    
    @staticmethod
    def is_text_number(text: str) -> bool:
        """判断是否为文本型数字（如账号、订单号）"""
        if not text:
            return False
        
        clean_text = re.sub(r'[\s-]', '', text)
        
        if clean_text.isdigit() and len(clean_text) > 15:
            return True
        
        if re.match(r'^[\d\s-]+$', text) and len(clean_text) > 10:
            return True
        
        return False
    
    @staticmethod
    def parse_number(text: str) -> float:
        """解析数字，处理千分位和货币符号"""
        if not text:
            return 0.0
        
        clean_text = re.sub(r'[¥$€£,，\s]', '', text)
        
        is_negative = False
        if clean_text.startswith('-') or clean_text.startswith('−'):
            is_negative = True
            clean_text = clean_text[1:]
        
        if clean_text.startswith('(') and clean_text.endswith(')'):
            is_negative = True
            clean_text = clean_text[1:-1]
        
        try:
            number = float(clean_text)
            return -number if is_negative else number
        except ValueError:
            return 0.0
    
    @staticmethod
    def extract_datetime(text: str) -> str:
        """提取并标准化日期时间"""
        patterns = [
            (r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})\s*(\d{1,2}):(\d{1,2}):(\d{1,2})', 
             lambda m: f"{m.group(1)}-{m.group(2).zfill(2)}-{m.group(3).zfill(2)} {m.group(4).zfill(2)}:{m.group(5).zfill(2)}:{m.group(6).zfill(2)}"),
            (r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})', 
             lambda m: f"{m.group(1)}-{m.group(2).zfill(2)}-{m.group(3).zfill(2)}"),
            (r'(\d{4})年(\d{1,2})月(\d{1,2})日', 
             lambda m: f"{m.group(1)}-{m.group(2).zfill(2)}-{m.group(3).zfill(2)}"),
        ]
        
        for pattern, formatter in patterns:
            match = re.search(pattern, text)
            if match:
                return formatter(match)
        
        return text
    
    @staticmethod
    def detect_column_type(column_values: List[str]) -> str:
        """检测列的数据类型"""
        if not column_values:
            return 'text'
        
        non_empty_values = [v for v in column_values if v and v.strip() and v not in ['/', '-']]
        if not non_empty_values:
            return 'text'
        
        # 检测文本型数字
        text_number_count = sum(1 for v in non_empty_values[:5] if DataTypeDetector.is_text_number(v))
        if text_number_count >= len(non_empty_values[:5]) * 0.6:
            return 'text'
        
        # 检测日期时间
        datetime_patterns = [
            r'\d{4}[-/]\d{1,2}[-/]\d{1,2}',
            r'\d{4}[-/]\d{1,2}[-/]\d{1,2}\s*\d{1,2}:\d{1,2}:\d{1,2}',
            r'\d{4}年\d{1,2}月\d{1,2}日',
        ]
        
        datetime_count = 0
        for value in non_empty_values[:5]:
            for pattern in datetime_patterns:
                if re.search(pattern, value):
                    datetime_count += 1
                    break
        
        if datetime_count >= len(non_empty_values[:5]) * 0.6:
            return 'datetime'
        
        # 检测数字
        numeric_count = sum(1 for v in non_empty_values[:5] 
                           if DataTypeDetector.is_numeric(v) and not DataTypeDetector.is_text_number(v))
        
        if numeric_count >= len(non_empty_values[:5]) * 0.6:
            return 'numeric'
        
        return 'text'
    
    @staticmethod
    def normalize_text_number(text: str) -> str:
        """标准化文本型数字：移除空格和连字符"""
        if not text:
            return ""
        return re.sub(r'[\s\-\u3000]', '', text)