"""
配置加载模块
从config.yaml文件加载配置参数
"""

import yaml
from pathlib import Path


class Config:
    """配置类，用于加载和访问配置参数"""
    
    _instance = None
    _config = None
    
    def __new__(cls):
        """单例模式"""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        """初始化配置"""
        if self._config is None:
            self.load_config()
    
    def load_config(self, config_path=None):
        """
        加载配置文件
        
        参数:
            config_path: 配置文件路径，默认为当前目录下的config.yaml
        """
        if config_path is None:
            # config.yaml 现在在同一目录下
            config_path = Path(__file__).parent / 'config.yaml'
        else:
            config_path = Path(config_path)
        
        if not config_path.exists():
            raise FileNotFoundError(f"配置文件不存在: {config_path}")
        
        with open(config_path, 'r', encoding='utf-8') as f:
            self._config = yaml.safe_load(f)
    
    def get(self, key_path, default=None):
        """
        获取配置值
        
        参数:
            key_path: 配置键路径，用点号分隔，如 'llm.model_url'
            default: 默认值
            
        返回:
            配置值
        """
        keys = key_path.split('.')
        value = self._config
        
        for key in keys:
            if isinstance(value, dict) and key in value:
                value = value[key]
            else:
                return default
        
        return value
    
    
    # 文本切分配置
    @property
    def target_level(self):
        return self.get('text_splitting.target_level', 2)
    
    @property
    def max_chunk_size(self):
        return self.get('text_splitting.max_chunk_size', 1000)
    
    @property
    def min_chunk_size(self):
        return self.get('text_splitting.min_chunk_size', 500)
    
    @property
    def fuzzy_threshold(self):
        return self.get('text_splitting.fuzzy_threshold', 0.80)
    
    # 目录提取配置
    @property
    def toc_max_pages(self):
        return self.get('toc_extraction.max_pages', 15)
    
    @property
    def paragraphs_per_page(self):
        return self.get('toc_extraction.paragraphs_per_page', 30)
    
    # 分类配置
    @property
    def category_mapping(self):
        return self.get('categories.mapping', {})
    
    
    @property
    def category_keywords(self):
        """获取分类关键词匹配规则"""
        return self.get('categories.keywords', {})
    
    # 输出配置
    @property
    def default_output_dir(self):
        return self.get('output.default_dir_name', '分类切分结果')
    
    @property
    def save_results_default(self):
        return self.get('output.save_results', True)
    
    @property
    def max_filename_length(self):
        return self.get('output.max_filename_length', 200)
    
    # 编号格式配置
    @property
    def numbering_formats(self):
        return self.get('numbering.formats', [])
    
    # 噪音过滤配置
    @property
    def noise_patterns(self):
        return self.get('noise_filters.patterns', [])
    
    # 目录检测配置
    @property
    def toc_patterns(self):
        return self.get('toc_detection.patterns', [])
    
    @property
    def toc_min_length(self):
        return self.get('toc_detection.min_length', 3)
    
    @property
    def toc_max_length(self):
        return self.get('toc_detection.max_length', 200)
    
    # 格式模式配置
    @property
    def format_patterns_templates(self):
        return self.get('format_patterns.templates', [])
    
    # 标题编号提取规则配置
    @property
    def title_number_extraction_rules(self):
        return self.get('numbering.extraction_rules', [])


# 全局配置实例
config = Config()


def get_config():
    """获取全局配置实例"""
    return config

