# LIB · 密钥管理模块
# D181 · 2026-07-10
"""统一密钥入口 · 永不硬编码 · 铁律①"""
import os

def get_ark_key():
    """获取火山方舟 ARK API Key
    
    查找顺序:
    1. 环境变量 ARK_API_KEY
    2. tools/secrets_loader.py 的 SC-001
    3. 苍耳本机仓库外密钥文件
    """
    # 1. 直接环境变量
    key = os.environ.get("ARK_API_KEY")
    if key:
        return key

    # 2. 通过 secrets_loader 的编号体系
    try:
        import sys
        tools_dir = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            "tools"
        )
        if tools_dir not in sys.path:
            sys.path.insert(0, tools_dir)
        from secrets_loader import secret
        key = secret("SC-001")
        if key:
            return key
    except Exception:
        pass

    # 3. 本机仓库外文件兜底（旧环境迁移兼容）
    for env_path in [
        os.environ.get("VIDEO_AI_SECRETS_FILE", ""),
        "/root/guanghulab-local-secrets/cang-ying.env",
        os.path.expanduser("~/guanghulab-local-secrets/cang-ying.env"),
        "/Users/bingshuolingdianyuanhe/Documents/guanghulab-local-secrets/video-ai-system.env",
    ]:
        if os.path.exists(env_path):
            try:
                with open(env_path, "r", encoding="utf-8") as f:
                    for line in f:
                        line = line.strip()
                        if "=" in line and not line.startswith("#"):
                            k, v = line.split("=", 1)
                            if k.strip() == "ARK_API_KEY":
                                return v.strip()
            except Exception:
                continue

    raise RuntimeError(
        "🔑 ARK_API_KEY 未找到。\n"
        "  请设置环境变量: export ARK_API_KEY=ark-xxx\n"
        "  或配置 SC-001: tools/secrets_loader.py\n"
        "  或在苍耳本机仓库外密钥文件中配置 ARK_API_KEY\n"
        "  ⊢ 铁律① · 密钥永远不放代码仓库"
    )
