"""AI 模块配置 — 从环境变量加载 DashScope 相关参数。

所有 DASHSCOPE_* 环境变量和 INTERNAL_API_TOKEN 统一在此管理，
启动时通过 from_env() 校验必需变量，缺失立即报错。
"""

from __future__ import annotations

import os
from dataclasses import dataclass


@dataclass(frozen=True)
class AIConfig:
    """AI 模块配置，从环境变量加载。不可变（frozen）。"""

    api_key: str                       # DASHSCOPE_API_KEY
    workspace_id: str | None           # DASHSCOPE_WORKSPACE_ID（可选）
    app_id_1_chat: str                 # DASHSCOPE_APP_ID_1_CHAT
    app_id_2_finance: str              # DASHSCOPE_APP_ID_2_FINANCE
    app_id_2a_finance_area: str        # DASHSCOPE_APP_ID_2A_FINANCE_AREA（2026-04-23 新增，区域财务洞察）
    app_id_3_clue: str                 # DASHSCOPE_APP_ID_3_CLUE
    app_id_4_analysis: str             # DASHSCOPE_APP_ID_4_ANALYSIS
    app_id_5_tactics: str              # DASHSCOPE_APP_ID_5_TACTICS
    app_id_6_note: str                 # DASHSCOPE_APP_ID_6_NOTE
    app_id_7_customer: str             # DASHSCOPE_APP_ID_7_CUSTOMER
    app_id_8_consolidate: str          # DASHSCOPE_APP_ID_8_CONSOLIDATE
    internal_api_token: str            # INTERNAL_API_TOKEN

    @classmethod
    def from_env(cls) -> AIConfig:
        """从环境变量加载配置。

        必需变量缺失时立即抛出 ValueError，禁止静默回退空字符串。
        可选变量（DASHSCOPE_WORKSPACE_ID）缺失时为 None。
        """
        required_mapping: dict[str, str] = {
            "DASHSCOPE_API_KEY": "api_key",
            "DASHSCOPE_APP_ID_1_CHAT": "app_id_1_chat",
            "DASHSCOPE_APP_ID_2_FINANCE": "app_id_2_finance",
            "DASHSCOPE_APP_ID_2A_FINANCE_AREA": "app_id_2a_finance_area",
            "DASHSCOPE_APP_ID_3_CLUE": "app_id_3_clue",
            "DASHSCOPE_APP_ID_4_ANALYSIS": "app_id_4_analysis",
            "DASHSCOPE_APP_ID_5_TACTICS": "app_id_5_tactics",
            "DASHSCOPE_APP_ID_6_NOTE": "app_id_6_note",
            "DASHSCOPE_APP_ID_7_CUSTOMER": "app_id_7_customer",
            "DASHSCOPE_APP_ID_8_CONSOLIDATE": "app_id_8_consolidate",
            "INTERNAL_API_TOKEN": "internal_api_token",
        }

        # 收集所有缺失的必需变量，一次性报错
        missing: list[str] = []
        values: dict[str, str] = {}

        for env_name, field_name in required_mapping.items():
            val = os.environ.get(env_name)
            if not val:  # None 或空字符串均视为缺失
                missing.append(env_name)
            else:
                values[field_name] = val

        if missing:
            raise ValueError(
                f"AI 配置缺失必需环境变量: {', '.join(missing)}"
            )

        # 可选变量
        workspace_id = os.environ.get("DASHSCOPE_WORKSPACE_ID") or None

        return cls(workspace_id=workspace_id, **values)
