#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
配置类与全局变量

注意：
1. LLM 调用已统一通过 foundation.ai.agent.generate.model_generate 处理
2. Embedding 模型已统一通过 foundation.ai.models.model_handler 处理
本配置类仅保留并发控制和路径配置
"""

from pathlib import Path
from dataclasses import dataclass, field
from typing import Optional

from foundation.observability.logger.loggering import review_logger as logger


def _load_model_from_yaml() -> str:
    """从 model_setting.yaml 加载默认模型配置

    优先读取 doc_classification_tertiary 配置，其次使用 default 配置
    """
    try:
        import yaml
        yaml_path = Path(__file__).parent.parent.parent.parent.parent.parent.parent / "config" / "model_setting.yaml"
        logger.debug(f"[ClassifierConfig] 尝试加载模型配置: {yaml_path}")
        if yaml_path.exists():
            with open(yaml_path, 'r', encoding='utf-8') as f:
                settings = yaml.safe_load(f)
                model_settings = settings.get('model_settings', {})
                # 优先使用三级分类配置
                tertiary_config = model_settings.get('doc_classification_tertiary', {})
                if tertiary_config and 'model' in tertiary_config:
                    model = tertiary_config['model']
                    logger.info(f"[ClassifierConfig] 从 model_setting.yaml 加载三级分类模型: {model}")
                    return model
                # 其次使用默认配置
                default_config = settings.get('default', {})
                if default_config and 'model' in default_config:
                    model = default_config['model']
                    logger.info(f"[ClassifierConfig] 从 model_setting.yaml 加载默认模型: {model}")
                    return model
        else:
            logger.warning(f"[ClassifierConfig] model_setting.yaml 不存在: {yaml_path}")
    except Exception as e:
        logger.warning(f"[ClassifierConfig] 加载 model_setting.yaml 失败: {e}")
    logger.info("[ClassifierConfig] 使用兜底默认模型: qwen3_5_35b_a3b")
    return "qwen3_5_35b_a3b"  # 兜底默认值


def _load_thinking_mode_from_yaml() -> bool:
    """从 model_setting.yaml 加载 thinking 模式配置"""
    try:
        import yaml
        yaml_path = Path(__file__).parent.parent.parent.parent.parent.parent.parent / "config" / "model_setting.yaml"
        if yaml_path.exists():
            with open(yaml_path, 'r', encoding='utf-8') as f:
                settings = yaml.safe_load(f)
                model_settings = settings.get('model_settings', {})
                tertiary_config = model_settings.get('doc_classification_tertiary', {})
                if tertiary_config and 'enable_thinking' in tertiary_config:
                    thinking = tertiary_config['enable_thinking']
                    logger.debug(f"[ClassifierConfig] 从 model_setting.yaml 加载 thinking 模式: {thinking}")
                    return thinking
    except Exception as e:
        logger.debug(f"[ClassifierConfig] 加载 thinking 模式失败: {e}")
    return False  # 默认禁用 thinking 模式


@dataclass
class ClassifierConfig:
    """分类器配置

    注意：
    - LLM 调用统一通过 generate_model_client 处理
    - Embedding 模型统一通过 model_handler.get_embedding_model() 处理
    本配置仅用于控制并发和路径
    """

    # LLM 模型名称（从 model_setting.yaml 自动加载，可覆盖）
    model: str = field(default_factory=_load_model_from_yaml)

    # 是否启用 thinking 模式（从 model_setting.yaml 自动加载）
    enable_thinking: bool = field(default_factory=_load_thinking_mode_from_yaml)

    # 并发控制
    max_concurrent_requests: int = 20
    max_retries: int = 3
    retry_delay: int = 1

    # Embedding 相似度阈值（仅阈值配置保留在此处）
    embedding_similarity_threshold: float = 0.9

    # 路径配置（通过 __post_init__ 自动初始化）
    category_table_path: str = ""
    second_category_path: str = ""
    output_path: str = ""

    def __post_init__(self):
        """初始化路径配置"""
        # 初始化默认路径
        # 注意：本文件位于 reviewers/utils/llm_content_classifier_v2/config.py
        # parent.parent.parent.parent = component/
        if not self.category_table_path:
            self.category_table_path = str(
                Path(__file__).parent.parent.parent.parent / "doc_worker" / "config" / "StandardCategoryTable.csv"
            )
        if not self.second_category_path:
            self.second_category_path = str(
                Path(__file__).parent.parent.parent.parent / "doc_worker" / "config" / "construction_plan_standards.csv"
            )
        if not self.output_path:
            # 项目根目录下的 temp/construction_review/llm_content_classifier_v2
            # 从 reviewers/utils/llm_content_classifier_v2/ 向上 7 层到项目根目录
            project_root = Path(__file__).parent.parent.parent.parent.parent.parent.parent
            self.output_path = str(project_root / "temp" / "construction_review" / "llm_content_classifier_v2")

    def get_embedding_model(self):
        """
        获取 Embedding 模型实例

        统一通过 model_handler 获取，配置从 config.ini 读取

        Returns:
            OpenAIEmbeddings: 配置好的 Embedding 模型实例
        """
        from foundation.ai.models.model_handler import model_handler
        return model_handler.get_embedding_model()


# 默认配置实例
DEFAULT_CONFIG = ClassifierConfig()

# 向后兼容的全局变量（供独立运行测试使用）
# 注意：api_key 和 base_url 已从 ClassifierConfig 移除，LLM 配置由 model_generate 统一处理
MAX_CONCURRENT_REQUESTS = DEFAULT_CONFIG.max_concurrent_requests
MAX_RETRIES = DEFAULT_CONFIG.max_retries
RETRY_DELAY = DEFAULT_CONFIG.retry_delay
MODEL = DEFAULT_CONFIG.model
EMBEDDING_SIMILARITY_THRESHOLD = DEFAULT_CONFIG.embedding_similarity_threshold
CATEGORY_TABLE_PATH = Path(DEFAULT_CONFIG.category_table_path)
SECOND_CATEGORY_PATH = Path(DEFAULT_CONFIG.second_category_path)
