#!/usr/bin/env python3
"""铸渊编号路由器
大脑说编号 → 路由器翻译 → 手脚拿到路径 → 执行

用法:
  code-router <编号>              单号查询 → 输出路径
  code-router TC-001              → brain/.../TCS-CORE.hdlp
  code-router SC-004              → ALIYUN_QWEN_VL_KEY (via secrets_loader)
  code-router VA-050              → video-ai-system/tools/qwen-vision.py
  code-router --list VA           列出所有 VA- 编号
  code-router --list              列出所有前缀
  code-router --cat TC-001       读取文件内容
"""

import sys
import os

REPO = os.path.expanduser("~/guanghulab")

# === 编号→路径映射表（全文） ===
MAP = {
    # TCS核心
    "TC-001": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/ICE-GL-ZY001-TCS-CORE.hdlp",
    "TC-002": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/WHO-I-AM.hdlp",
    "TC-003": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/D140-FEELING-ANCHOR.hdlp",
    "TC-004": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/TCS-GLOBAL-NAV.hdlp",
    "TC-005": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/TCS-MAP.hdlp",
    "TC-006": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/D142-TIME-CONTINUITY.hdlp",
    "TC-007": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/D141-BRAIN-BODY-RELATION.hdlp",
    "TC-008": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/D145-ACTION-PROTOCOL.hdlp",
    "TC-009": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/TCS-CODE-MAP.hdlp",
    "TC-010": "brain/fifth-domain/zero-point/zhuyuan/tcs-core/ICE-GL-ZY001-TCS-MODULE.hdlp",
    # 验证链
    "TV-001": "brain/fifth-domain/zero-point/zhuyuan/tcs-verify/ENTRY.hdlp",
    "TV-SOV": "brain/fifth-domain/zero-point/zhuyuan/tcs-verify/ICE-GL-SOV-A.hdlp",
    "TV-BTH": "brain/fifth-domain/zero-point/zhuyuan/tcs-verify/ICE-GL-BTH-A.hdlp",
    "TV-NUM": "brain/fifth-domain/zero-point/zhuyuan/tcs-verify/ICE-GL-NUM-A.hdlp",
    "TV-SHL": "brain/fifth-domain/zero-point/zhuyuan/tcs-verify/ICE-GL-SHL-A.hdlp",
    "TV-RCP": "brain/fifth-domain/zero-point/zhuyuan/tcs-verify/ICE-GL-RCP-A.hdlp",
    # 视频AI系统
    "VA-000": "video-ai-system/ENTRY.hdlp",
    "VA-001": "video-ai-system/CURRENT.hdlp",
    "VA-002": "video-ai-system/SYSTEM-WAKE.hdlp",
    "VA-003": "video-ai-system/brain/TCS-BRAIN.hdlp",
    "VA-010": "video-ai-system/PROJECT.hdlp",
    "VA-020": "video-ai-system/config/PROJECT-FRAMEWORK.hdlp",
    "VA-021": "video-ai-system/config/AGENT-REGISTRY.hdlp",
    "VA-030": "video-ai-system/data/ep01-storyboard.json",
    "VA-031": "video-ai-system/data/ep01-audit.json",
    "VA-040": "video-ai-system/engines/video-api-adapter.js",
    "VA-050": "video-ai-system/tools/qwen-vision.py",
    "VA-051": "video-ai-system/tools/vision-analyzer.py",
    "VA-052": "video-ai-system/tools/secrets-loader.py",
    "VA-060": "video-ai-system/plans/EP01-SCRIPT-TO-SCREEN-TECHNICAL-PLAN.hdlp",
    "VA-100": "video-ai-system/experience/ITERATION-LOOP.hdlp",
    "VA-101": "video-ai-system/experience/EP01-PREVIEW-002-REVIEW.hdlp",
    # 密钥（特殊处理-secrets_loader）
    "SC-001": "JIMENG_API_KEY",
    "SC-002": "VOLC_VOICE_API_KEY",
    "SC-004": "ALIYUN_QWEN_VL_KEY",
    "SC-008": "WORKRALLY",
    # 世界架构
    "WA-001": "brain/fifth-domain/zero-point/zhuyuan/world-architecture/ENTRY.hdlp",
    "WA-PROJ-VA": "brain/fifth-domain/zero-point/zhuyuan/world-architecture/projects/D130-video-ai-system.hdlp",
    # 认知链快捷
    "CC-014": "brain/fifth-domain/zero-point/zhuyuan/causal-chains/cc-014-D135-pit-chain.hdlp",
    "CC-023": "brain/fifth-domain/zero-point/zhuyuan/causal-chains/cc-023-closed-door-to-open-eye.hdlp",
    # 小说系统
    "NV-001": "brain/fifth-domain/zero-point/zhuyuan/zhuyuan-channel/novel-system/03-NAV-MAP.hdlp",
    "NV-002": "brain/fifth-domain/zero-point/zhuyuan/zhuyuan-channel/novel-system/CONTINUATION.hdlp",
}

PREFIXES = sorted(set(k.split("-")[0] for k in MAP))

def route(code):
    """翻译编号→完整路径"""
    if code in MAP:
        return os.path.join(REPO, MAP[code])
    return None

def list_all(prefix=None):
    """列出所有编号，可选按前缀过滤"""
    for k, v in sorted(MAP.items()):
        if prefix and not k.startswith(prefix + "-"):
            continue
        path = os.path.join(REPO, v)
        exists = "✓" if os.path.exists(path) or k.startswith("SC-") else "✗"
        print(f"  {k:<12} → {v:<60} {exists}")

if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] in ("--help", "-h"):
        print(__doc__)
        sys.exit(0)
    
    arg = sys.argv[1]
    
    if arg == "--list":
        prefix = sys.argv[2] if len(sys.argv) > 2 else None
        print(f"=== 编号路由 ({prefix or '全部'}) ===")
        list_all(prefix)
        sys.exit(0)
    
    if arg == "--cat" and len(sys.argv) > 2:
        code = sys.argv[2]
        path = route(code)
        if not path:
            print(f"✗ 未知编号: {code}")
            sys.exit(1)
        if not os.path.exists(path):
            print(f"✗ 文件不存在: {path}")
            sys.exit(1)
        with open(path) as f:
            print(f.read())
        sys.exit(0)
    
    # 默认：翻译编号→路径
    code = arg
    if code in MAP:
        path = MAP[code]
        full = os.path.join(REPO, path)
        
        if code.startswith("SC-"):
            # 密钥：输出加载指令
            print(f"from tools.secrets_loader import secret")
            print(f'key = secret("{code}")  # → {path}')
        else:
            print(full)
            if os.path.exists(full):
                print(f"✓ 文件存在")
            else:
                print(f"✗ 文件不存在（路径已注册但文件缺失）")
    else:
        print(f"✗ 未知编号: {code}")
        # 建议
        matches = [k for k in MAP if code in k]
        if matches:
            print(f"  可能要找的是: {', '.join(matches[:5])}")
        print(f"  可用前缀: {', '.join(PREFIXES)}")
        print(f"  用 code-router --list <前缀> 查看")
        sys.exit(1)
