#!/usr/bin/env python3
"""
atdc 命令生成器 — 一键创建跨 4 端的新命令

用法:
  python3 add-command.py <name> <desc> <trigger_words> [--prompt X-xxx]

示例:
  python3 add-command.py my-cmd "我的命令描述" "my-cmd、我的命令"
  python3 add-command.py table2xlsx "DDL→Excel" "table2xlsx、生成模板" --prompt X-table2xlsx
"""

import os, sys, argparse

ATD = os.path.expanduser("~/atdc")

TEMPLATES = {
    "opencode": """---
description: {desc}，跳过自动路由
---
用 Read 工具读取 ${ATDC_DIR}/prompts/{prompt}.md，然后直接开始执行。

$ARGUMENTS
""",
    "claude": """用 Read 工具读取 ${ATDC_DIR}/prompts/{prompt}.md，然后直接开始执行。
跳过 GO.md 路由。

$ARGUMENTS
""",
    "codex": """---
name: atd:{name}
description: {desc}。触发词：{triggers}。
---
用 Read 工具读取 `${ATDC_DIR}/prompts/{prompt}.md`，然后直接开始执行。
""",
    "cursor": """---
name: atd:{name}
description: {desc}。触发词：{triggers}。
---
用 Read 工具读取 `${ATDC_DIR}/prompts/{prompt}.md`，然后直接开始执行。
""",
}

PATHS = {
    "opencode": f"{ATD}/commands/opencode/atdc/{{name}}.md",
    "claude": f"{ATD}/commands/claude/atdc/{{name}}.md",
    "codex": f"{ATD}/commands/codex/atdc-{{name}}/SKILL.md",
    "cursor": f"{ATD}/commands/cursor/atdc-{{name}}/SKILL.md",
}

def add_command(name, desc, triggers, prompt=None, short_desc=None, from_learn=False, failure=None, dead_end=None):
    if prompt is None:
        prompt = f"X-{name}"
    if short_desc is None:
        short_desc = desc[:30]

    for platform, tmpl in TEMPLATES.items():
        path = PATHS[platform].format(name=name)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        content = tmpl.format(name=name, desc=desc, triggers=triggers,
                              prompt=prompt, short_desc=short_desc, ATDC_DIR=ATD)
        with open(path, "w") as f:
            f.write(content)
        print(f"  ✓ {platform:10s} {path}")

    # create prompt template
    prompt_path = f"{ATD}/prompts/{prompt}.md"
    if not os.path.exists(prompt_path):
        os.makedirs(os.path.dirname(prompt_path), exist_ok=True)
        if from_learn:
            with open(prompt_path, "w") as f:
                f.write(f"# prompts/{prompt} · {short_desc}\n\n")
                f.write(f"横向命令，任意时刻可触发：`/atdc:{name} <args>`\n\n")
                f.write(f"> 🧠 Auto-harvested by self-learning\n\n")
                f.write("---\n\n")
                if failure:
                    f.write(f"## 失败模式\n\n")
                    f.write(f"**这个 skill 避免的诊断**：`{failure}`\n\n")
                f.write("## 执行步骤\n\n")
                f.write("### 1. 确定输入\n\n")
                f.write("### 2. 执行\n\n")
                f.write("---\n\n")
                if dead_end:
                    f.write(f"## What didn't work\n\n")
                    f.write(f"- `{dead_end}`：被排除\n\n")
                f.write("## 验证方式\n\n")
                f.write("`<passing check — 什么命令/测试验证了这个路径>`\n\n")
        else:
            with open(prompt_path, "w") as f:
                f.write(f"# prompts/{prompt} · {short_desc}\n\n")
                f.write(f"横向命令，任意时刻可触发：`/atdc:{name} <args>`\n\n")
                f.write("## 执行步骤\n\n")
                f.write("### 1. 确定输入\n\n")
                f.write("### 2. 执行\n\n")
        print(f"  ✓ prompt    {prompt_path}")

    # update install.sh skill list
    install_sh = f"{ATD}/install.sh"
    with open(install_sh) as f:
        content = f.read()

    skill_name = f"atdc-{name}"
    marker = "for skill in atdc "
    if marker in content and skill_name not in content:
        # Find the "for skill in" line and add the new skill
        lines = content.split("\n")
        for i, line in enumerate(lines):
            if "for skill in atdc " in line and skill_name not in line:
                # Insert before the "do" keyword
                j = line.rfind("; do")
                if j < 0:
                    continue
                lines[i] = line[:j] + f" {skill_name}" + line[j:]
                break
        with open(install_sh, "w") as f:
            f.write("\n".join(lines))
        print(f"  ✓ install.sh {skill_name} 已注册")
    else:
        print(f"  - install.sh {skill_name} 已存在或无需更新")

    # create agents/skills symlink
    agents_skill = os.path.expanduser(f"~/.agents/skills/{skill_name}")
    target = f"{ATD}/commands/codex/{skill_name}"
    if not os.path.islink(agents_skill):
        os.symlink(target, agents_skill)
        print(f"  ✓ symlink   {agents_skill} -> {target}")

    print(f"\n✅ 命令 /atdc:{name} 已创建（4 端 + prompt + install.sh + symlink）")
    print(f"   重启各终端 Ctrl+C 重进即可使用。")


if __name__ == "__main__":
    p = argparse.ArgumentParser(description="atdc 命令生成器")
    p.add_argument("name", help="命令名 (kebab-case, 如 my-cmd)")
    p.add_argument("desc", help="命令描述")
    p.add_argument("triggers", help="触发词 (逗号分隔, 如 'cmd、命令')")
    p.add_argument("--prompt", help="prompt 文件名 (默认 X-<name>)")
    p.add_argument("--short", help="简短描述 (body 结尾句)")
    p.add_argument("--from-learn", action="store_true", help="从 self-learning harvest 生成（使用 learn-skill 模板）")
    p.add_argument("--failure", help="这个 skill 避免/诊断的失败模式")
    p.add_argument("--dead-end", help="被排除的死路方案")
    args = p.parse_args()
    add_command(args.name, args.desc, args.triggers, args.prompt, args.short,
                from_learn=args.from_learn, failure=args.failure, dead_end=args.dead_end)
