"""
目录模式匹配模块
用于检测和匹配目录项的模式
"""

import re

try:
    from ..config.config_loader import get_config
except ImportError:
    from config.config_loader import get_config


class TOCPatternMatcher:
    """目录模式匹配器"""
    
    def __init__(self):
        self.config = get_config()
    
    def has_numbering(self, text):
        """检查文本是否包含编号格式"""
        numbering_patterns = self.config.numbering_formats
        
        for pattern in numbering_patterns:
            if re.match(pattern, text):
                return True
        
        return False
    
    def detect_toc_patterns(self, text):
        """检测文本中的目录模式"""
        toc_items = []
        lines = text.split('\n')
        
        # 预处理：合并可能分行的目录项
        merged_lines = []
        i = 0
        while i < len(lines):
            line = lines[i].strip()
            
            if re.match(r'^第[一二三四五六七八九十\d]+[章节条款]\s*$', line):
                if i + 1 < len(lines):
                    next_line = lines[i + 1].strip()
                    if re.search(r'[.·]{2,}.*\d{1,4}\s*$', next_line):
                        merged_line = line + next_line
                        merged_lines.append(merged_line)
                        i += 2
                        continue
            
            merged_lines.append(line)
            i += 1
        
        # 从配置读取目录格式的正则表达式
        patterns = self.config.toc_patterns
        
        # 从配置读取长度限制
        min_length = self.config.toc_min_length
        max_length = self.config.toc_max_length
        
        for line in merged_lines:
            line = line.strip()
            
            if len(line) < min_length or len(line) > max_length:
                continue
            
            if line.isdigit():
                continue
            
            for pattern in patterns:
                match = re.match(pattern, line)
                if match:
                    title = match.group(1).strip()
                    page_num = match.group(2).strip()
                    
                    title_clean = re.sub(r'[.·]{2,}', '', title)
                    title_clean = re.sub(r'\s{2,}', ' ', title_clean)
                    title_clean = title_clean.strip()
                    
                    if title_clean and not self.is_likely_noise(title_clean):
                        toc_items.append({
                            'original': line,
                            'title': title_clean,
                            'page': page_num,
                            'level': 1  # 初始层级，后续会通过递归识别重新设置
                        })
                        break
        
        return toc_items
    
    def is_likely_noise(self, text):
        """判断文本是否可能是噪音（非目录内容）"""
        noise_patterns = self.config.noise_patterns
        
        for pattern in noise_patterns:
            if re.search(pattern, text):
                return True
        
        return False


