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

from pathlib import Path
from typing import Tuple
from dataclasses import dataclass

from foundation.infrastructure.config.config import config_handler


def _get_llm_config_from_ini(model_type: str) -> Tuple[str, str, str]:
    """
    从 config.ini 获取 LLM 配置

    Args:
        model_type: 模型类型（如 qwen3_5_122b_a10b）

    Returns:
        Tuple[str, str, str]: (api_key, base_url, model_id)
    """
    try:
        # 尝试读取 DashScope 格式配置
        base_url = config_handler.get(model_type, "DASHSCOPE_SERVER_URL", "")
        model_id = config_handler.get(model_type, "DASHSCOPE_MODEL_ID", "")
        api_key = config_handler.get(model_type, "DASHSCOPE_API_KEY", "")

        # 如果没有 DashScope 配置，尝试读取其他格式
        if not base_url:
            # 尝试 QWEN_SERVER_URL 格式
            base_url = config_handler.get(model_type, f"{model_type.upper()}_SERVER_URL", "")
            model_id = config_handler.get(model_type, f"{model_type.upper()}_MODEL_ID", "")
            api_key = config_handler.get(model_type, f"{model_type.upper()}_API_KEY", "")

        return api_key, base_url, model_id
    except Exception:
        return "", "", ""


def _get_embedding_config_from_ini(embedding_model_type: str) -> Tuple[str, str, str]:
    """
    从 config.ini 获取 Embedding 模型配置

    Args:
        embedding_model_type: Embedding 模型类型

    Returns:
        Tuple[str, str, str]: (api_key, base_url, model_id)
    """
    try:
        # 本地 Embedding 模型
        if embedding_model_type == "lq_qwen3_8b_emd":
            base_url = config_handler.get("lq_qwen3_8b_emd", "LQ_EMBEDDING_SERVER_URL", "")
            model_id = config_handler.get("lq_qwen3_8b_emd", "LQ_EMBEDDING_MODEL_ID", "Qwen3-Embedding-8B")
            api_key = config_handler.get("lq_qwen3_8b_emd", "LQ_EMBEDDING_API_KEY", "dummy")
            return api_key, base_url, model_id

        # 硅基流动 Embedding 模型
        elif embedding_model_type == "siliconflow_embed":
            base_url = config_handler.get("siliconflow_embed", "SLCF_EMBED_SERVER_URL", "")
            model_id = config_handler.get("siliconflow_embed", "SLCF_EMBED_MODEL_ID", "Qwen/Qwen3-Embedding-8B")
            api_key = config_handler.get("siliconflow_embed", "SLCF_EMBED_API_KEY", "")
            return api_key, base_url, model_id

        return "", "", ""
    except Exception:
        return "", "", ""


@dataclass
class ClassifierConfig:
    """分类器配置（从 config.ini 加载）"""

    # LLM API 配置（从 config.ini 加载）
    api_key: str = ""
    base_url: str = ""
    model: str = ""

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

    # Embedding 配置（从 config.ini 加载）
    embedding_api_key: str = ""
    embedding_base_url: str = ""
    embedding_model: str = ""
    embedding_similarity_threshold: float = 0.9

    # 路径配置
    category_table_path: str = ""
    second_category_path: str = ""
    output_path: str = ""

    def __post_init__(self):
        """从 config.ini 加载配置"""
        # 加载 LLM 配置
        llm_model_type = config_handler.get("model", "COMPLETENESS_REVIEW_MODEL_TYPE", "qwen3_5_122b_a10b")
        api_key, base_url, model_id = _get_llm_config_from_ini(llm_model_type)

        # 设置 LLM 配置（如果从 config.ini 读取成功）
        if api_key:
            self.api_key = api_key
        if base_url:
            self.base_url = base_url
        if model_id:
            self.model = model_id

        # 加载 Embedding 配置
        embedding_model_type = config_handler.get("model", "EMBEDDING_MODEL_TYPE", "lq_qwen3_8b_emd")
        emb_api_key, emb_base_url, emb_model_id = _get_embedding_config_from_ini(embedding_model_type)

        if emb_api_key:
            self.embedding_api_key = emb_api_key
        if emb_base_url:
            self.embedding_base_url = emb_base_url
        if emb_model_id:
            self.embedding_model = emb_model_id

        # 初始化默认路径
        # 注意：本文件位于 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")


# 默认配置实例（从 config.ini 加载，用于独立运行测试）
DEFAULT_CONFIG = ClassifierConfig()

# 向后兼容的全局变量（供独立运行测试使用，从 config.ini 加载）
API_KEY = DEFAULT_CONFIG.api_key
MAX_CONCURRENT_REQUESTS = DEFAULT_CONFIG.max_concurrent_requests
MAX_RETRIES = DEFAULT_CONFIG.max_retries
RETRY_DELAY = DEFAULT_CONFIG.retry_delay
BASE_URL = DEFAULT_CONFIG.base_url
MODEL = DEFAULT_CONFIG.model
EMBEDDING_API_KEY = DEFAULT_CONFIG.embedding_api_key
EMBEDDING_BASE_URL = DEFAULT_CONFIG.embedding_base_url
EMBEDDING_MODEL = DEFAULT_CONFIG.embedding_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)
