#!/usr/bin/env python3
"""视频AI系统 · 统一密钥加载器 · 编号路由版

编号→变量名→路径→密钥值，全部路由见 LOCAL-SECRETS-PATH.hdlp。

用法:
  from tools.secrets_loader import secret, endpoint
  key = secret("ZY-SEC-004")     # 阿里千问VL视觉密钥
  url = endpoint("ZY-EPT-002")   # QWEN VL端点
"""

import os, json

# === 编号→变量名映射表（与 LOCAL-SECRETS-PATH.hdlp 同步）===
_SECRET_MAP = {
    "SC-001": "JIMENG_API_KEY",
    "SC-002": "VOLC_VOICE_API_KEY",
    "SC-003": "VOLC_VOICE_ACCESS_TOKEN",
    "SC-004": "ALIYUN_QWEN_VL_KEY",
    "SC-005": "ALIYUN_WANXIANG_KEY",
    "SC-006": "KLING_API_KEY",
    "SC-007": "ALIYUN_API_KEY",
    "SC-008": "WORKRALLY_API_KEY",
    "SC-009": "VOLC_VOICE_APP_ID",
    "SC-010": "VOLC_VOICE_SECRET_KEY",
    # 旧编号兼容
    "ZY-SEC-001": "JIMENG_API_KEY",
    "ZY-SEC-004": "ALIYUN_QWEN_VL_KEY",
}

_ENDPOINT_MAP = {
    "EPT-001": ("JIMENG_BASE_URL", "https://ark.cn-beijing.volces.com/api/v3"),
    "EPT-002": ("ALIYUN_QWEN_VL_ENDPOINT", "https://ws-umd6xwlovzmshuat.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"),
    "EPT-003": ("ALIYUN_BAILIAN_BASE_URL", "https://dashscope.aliyuncs.com/api/v1"),
    "EPT-004": ("WORKRALLY_ENDPOINT", "https://workrally.qq.com/zenstudio/api/mcp"),
}

# 密钥文件路径（按优先级: 低→高，后面覆盖前面）
_SECRET_FILES = [
    os.path.expanduser("~/guanghulab/video-ai-system/.env"),
    "/Users/bingshuolingdianyuanhe/Documents/guanghulab-local-secrets/video-ai-system.env",
]

# === WorkRally 特殊处理 ===
_WORKRALLY_CONFIG = os.path.expanduser("~/.workrally/config.json")

# === 加载 ===
_raw = {}

def _load_all():
    global _raw
    if _raw:
        return
    for path in _SECRET_FILES:
        if os.path.exists(path):
            with open(path) as f:
                for line in f:
                    line = line.strip()
                    if not line or line.startswith("#") or "=" not in line:
                        continue
                    k, v = line.split("=", 1)
                    k, v = k.strip(), v.strip()
                    _raw[k] = v
    # 环境变量最高优先级
    for k in list(_raw.keys()):
        env_val = os.environ.get(k)
        if env_val:
            _raw[k] = env_val
    # WorkRally
    if os.path.exists(_WORKRALLY_CONFIG):
        try:
            wr = json.load(open(_WORKRALLY_CONFIG))
            _raw["WORKRALLY_API_KEY"] = wr.get("api_key", "")
            _raw["WORKRALLY_ENDPOINT"] = wr.get("endpoint", "")
        except:
            pass

def secret(code_or_var, default=None):
    """按编号或变量名获取密钥值"""
    _load_all()
    var_name = _SECRET_MAP.get(code_or_var, code_or_var)  # 查编号映射，或直接当变量名
    if code_or_var == "ZY-SEC-008":
        return _raw.get("WORKRALLY_API_KEY", default)
    return _raw.get(var_name, default)

def endpoint(code_or_var, default=None):
    """按编号或变量名获取端点"""
    _load_all()
    var_name, fallback = _ENDPOINT_MAP.get(code_or_var, (code_or_var, ""))
    val = _raw.get(var_name, "")
    return val if val else (fallback if fallback else default)

if __name__ == "__main__":
    _load_all()
    print("=== 密钥编号 → 变量名 → 值（脱敏）===")
    for code, var in _SECRET_MAP.items():
        val = _raw.get(var, "")
        masked = val[:6] + "..." + val[-4:] if len(val) > 10 else ("***" if val else "(空)")
        print(f"  {code} → {var} = {masked}")
    print("  ZY-SEC-008 → WORKRALLY = ", end="")
    wr = _raw.get("WORKRALLY_API_KEY", "")
    print(f"{wr[:6]}...{wr[-4:]}" if len(wr) > 10 else "(空)")
