#!/usr/bin/env python3
"""secrets-loader.py · 统一密钥加载 · 编号路由
读 LOCAL-SECRETS-PATH.hdlp 规定的两个密钥文件，按编号返回密钥。
"""
import os

SECRET_PATHS = [
    "/Users/bingshuolingdianyuanhe/Documents/guanghulab-local-secrets/video-ai-system.env",
    os.path.expanduser("~/guanghulab/video-ai-system/.env"),
]

# 编号 → env变量名 映射
SECRET_MAP = {
    "SC-004": "ALIYUN_QWEN_VL_KEY",       # 阿里千问VL视觉
    "SC-005": "ALIYUN_BAILIAN_API_KEY",    # 阿里百炼通用
    "SC-001": "JIMENG_API_KEY",            # 火山即梦
}

ENDPOINT_MAP = {
    "EPT-002": "ALIYUN_QWEN_VL_ENDPOINT",  # 千问VL业务空间端点
    "EPT-001": "JIMENG_BASE_URL",           # 火山即梦端点
}

# 环境变量兜底值
ENDPOINT_DEFAULTS = {
    "EPT-002": "https://ws-umd6xwlovzmshuat.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation",
}

def _load_env():
    """按优先级加载所有密钥到内存"""
    env = dict(os.environ)
    for path in SECRET_PATHS:
        if os.path.exists(path):
            for line in open(path):
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                if "=" in line:
                    k, v = line.split("=", 1)
                    k, v = k.strip(), v.strip()
                    if v and k not in env:
                        env[k] = v
    return env

_ENV = _load_env()

def secret(code):
    """按编号返回密钥"""
    key_name = SECRET_MAP.get(code)
    if key_name:
        return _ENV.get(key_name, "")
    return ""

def endpoint(code):
    """按编号返回端点"""
    key_name = ENDPOINT_MAP.get(code)
    if key_name and _ENV.get(key_name):
        return _ENV[key_name]
    return ENDPOINT_DEFAULTS.get(code, "")
