# -*- coding: utf-8 -*-
"""从 upaibm_system 项目读取大模型配置（API Key、base_url）。"""
import json
import os
from pathlib import Path
from typing import Optional, Tuple

# 默认 upaibm_system 项目路径
UPAIBM_SYSTEM_ROOT = Path(r"D:\AllePro\upaibm_system")
CLAUDE_CONFIG_PATH = UPAIBM_SYSTEM_ROOT / "claude-config.json"
VLLM_MODEL_PATH = UPAIBM_SYSTEM_ROOT / "common" / "app" / "schemas" / "vllm_model.py"


def load_claude_config() -> Optional[dict]:
    """读取 claude-config.json，返回第一个带 api_key 的 Provider。"""
    if not CLAUDE_CONFIG_PATH.exists():
        return None
    try:
        with open(CLAUDE_CONFIG_PATH, "r", encoding="utf-8") as f:
            data = json.load(f)
        providers = data.get("Providers") or []
        for p in providers:
            key = (p.get("api_key") or "").strip()
            if key:
                return {
                    "api_base_url": (p.get("api_base_url") or "").strip(),
                    "api_key": key,
                    "name": p.get("name", ""),
                }
    except Exception:
        pass
    return None


def load_vllm_config() -> Optional[dict]:
    """从 vllm_model.py 读取 API_BASE 与 API_KEY（若存在）。"""
    if not VLLM_MODEL_PATH.exists():
        return None
    try:
        text = VLLM_MODEL_PATH.read_text(encoding="utf-8")
        api_base = None
        api_key = None
        for line in text.splitlines():
            line = line.strip()
            if line.startswith("API_BASE ="):
                api_base = line.split("=", 1)[1].strip().strip('"').strip("'")
            elif line.startswith("API_KEY ="):
                api_key = line.split("=", 1)[1].strip().strip('"').strip("'")
        if api_base and api_key:
            return {"api_base_url": api_base, "api_key": api_key, "name": "vllm"}
    except Exception:
        pass
    return None


def get_ai_config() -> Tuple[Optional[str], Optional[str]]:
    """
    获取用于调用大模型的 (api_base_url, api_key)。
    优先使用 claude-config.json，其次 vllm_model.py。
    """
    cfg = load_claude_config() or load_vllm_config()
    if not cfg:
        return None, None
    return cfg.get("api_base_url") or None, cfg.get("api_key") or None
