#!/usr/bin/env python3
"""泛化引擎 CLI —— 新项目脚手架初始化工具。

从当前规范体系模板生成新项目的 AGENTS.md + .agents/ 骨架，
将本项目的元规范框架"克隆"到任意新项目。

Usage:
    python -m agents init                    # 交互式向导
    python -m agents init --name "MyProject" --type software --lang zh
    python -m agents init --name "MyLib" --type library --lang en --roles developer,reviewer
    python -m agents init --dry-run          # 预览而不生成文件
"""


# 版本校验：导入共享库
import sys as _sys
from pathlib import Path as _Path
_sys.path.insert(0, str(_Path(__file__).resolve().parent / "lib"))

from python310_version_check import enforce_python310

enforce_python310()

import argparse
import shutil
import sys
from pathlib import Path

from lib.project import resolve_project_root
from lib.cli import print_header, print_pass, print_warn, print_summary

# ── 模板定义 ────────────────────────────────────────────────

AGENTS_MD_TEMPLATE = """# Agent Global Contract (AGENTS Manifest)

This file is the highest-priority entry point and context router for all AI agents.
All agents MUST read this file first, locate the appropriate `.agents/` specification
via the context routing table, then load role definitions, system prompts, and
collaboration protocols before executing tasks.

## Global Core Rules

- **Communication Language**: {language_rule}
- **On-Demand Loading**: Before domain-specific tasks, only read `.agents/` specs directly relevant to the current task. Avoid loading all context at once.
- **Context Economy**: Follow "search first, read precisely, keep only relevant context." Prioritize semantic search and exact matching tools.
- **Mermaid First**: Visual logic (flows, architecture, relationships, state machines) should use Mermaid. Renderable and versionable.
- **Code Changes**: Follow "convention over configuration." Prefer existing code style, naming conventions, and directory structure.
- **No Temporary Dependencies**: Do NOT commit `vendor/`, `.temp/`, `__pycache__/`, `.venv/`, `node_modules/` to Git.

## Role Index

{role_table}

## Context Routing Table

| Task Type | Required Entry |
|-----------|---------------|
| Role definitions & responsibilities | .agents/roles/ |
| System prompts & few-shot examples | .agents/prompts/ |
| Tool invocation specs | .agents/tools/ |
| Collaboration protocols | .agents/protocols/ |
| Standard workflows | .agents/workflows/ |
| Task & handoff templates | .agents/templates/ |
| Validation scripts | .agents/scripts/ |
"""

ROLE_DEFINITION_TEMPLATE = """---
id: "{role_id}"
domain: "{domain}"
layer: "{layer}"
x-toml-ref: "../../.meta/toml/.agents/roles/{role_id}.toml"
---

# {role_name}

## Responsibilities

{responsibilities}

## Non-Goals

{non_goals}
"""

GITIGNORE_TEMPLATE = """# Generated by agents init
vendor/
.temp/
__pycache__/
*.pyc
.venv/
node_modules/
.env
*.log
.DS_Store
Thumbs.db
"""

# ── 角色预设 ────────────────────────────────────────────────

ROLE_PRESETS = {
    "software": {
        "developer": {
            "role_id": "developer",
            "domain": "implementation",
            "layer": "execution",
            "role_name": "Developer",
            "responsibilities": "- Code implementation, refactoring, bug fixing\n- Unit test writing\n- Technical documentation",
            "non_goals": "- Do NOT make unilateral architecture decisions\n- Do NOT merge code without review",
        },
        "reviewer": {
            "role_id": "reviewer",
            "domain": "quality",
            "layer": "review",
            "role_name": "Code Reviewer",
            "responsibilities": "- Code quality review\n- Standards compliance checking\n- Security review",
            "non_goals": "- Do NOT modify business code directly\n- Do NOT perform acceptance testing",
        },
        "architect": {
            "role_id": "architect",
            "domain": "design",
            "layer": "architecture",
            "role_name": "Architect",
            "responsibilities": "- Technical architecture design\n- Technology selection\n- Design review",
            "non_goals": "- Do NOT implement code details\n- Do NOT write test cases",
        },
        "orchestrator": {
            "role_id": "orchestrator",
            "domain": "coordination",
            "layer": "orchestration",
            "role_name": "Orchestrator",
            "responsibilities": "- Task decomposition and assignment\n- Process coordination\n- Conflict arbitration",
            "non_goals": "- Do NOT write business code\n- Do NOT make technical decisions for architect",
        },
        "tester": {
            "role_id": "tester",
            "domain": "quality",
            "layer": "verification",
            "role_name": "Test Engineer",
            "responsibilities": "- Test case design and execution\n- Coverage analysis\n- Regression testing",
            "non_goals": "- Do NOT deploy to production\n- Do NOT modify business logic",
        },
    },
    "library": {
        "developer": {
            "role_id": "developer",
            "domain": "implementation",
            "layer": "execution",
            "role_name": "Developer",
            "responsibilities": "- API design and implementation\n- Documentation writing\n- Performance optimization",
            "non_goals": "- Do NOT break public API without deprecation notice\n- Do NOT introduce unnecessary dependencies",
        },
        "reviewer": {
            "role_id": "reviewer",
            "domain": "quality",
            "layer": "review",
            "role_name": "Reviewer",
            "responsibilities": "- API design review\n- Documentation review\n- Breaking change detection",
            "non_goals": "- Do NOT make API design decisions\n- Do NOT modify source directly",
        },
    },
}

LANG_RULES = {
    "zh": "All outputs, comments, commit messages, and documentation MUST be in Chinese.",
    "en": "All outputs, comments, commit messages, and documentation MUST be in English.",
}


# ── 生成器 ──────────────────────────────────────────────────

def generate_project(
    target_dir: Path,
    name: str,
    project_type: str,
    lang: str,
    roles: list[str],
    dry_run: bool = False,
) -> dict:
    """在目标目录生成项目骨架。

    Returns:
        {"created": [file_path, ...], "skipped": [file_path, ...], "errors": [...]}
    """
    result = {"created": [], "skipped": [], "errors": []}

    target_dir = target_dir.resolve()
    agents_dir = target_dir / ".agents"

    # ── 创建目录 ──
    if not dry_run:
        target_dir.mkdir(parents=True, exist_ok=True)

    # ── Step 1: Generate AGENTS.md ──
    agent_md_path = target_dir / "AGENTS.md"
    if agent_md_path.exists() and not dry_run:
        result["skipped"].append(str(agent_md_path))
    else:
        preset = ROLE_PRESETS.get(project_type, ROLE_PRESETS["software"])
        selected = {r: preset[r] for r in roles if r in preset}

        # Role table
        role_rows = []
        for rid, rdata in selected.items():
            role_rows.append(f"| {rdata['role_name']} | {rid} | {rdata['responsibilities'].split(chr(10))[0].strip('- ')} | .agents/roles/{rid}.md |")
        role_table = "| Role | ID | Responsibility | Entry |\n|---|---|---|---|\n" + "\n".join(role_rows)

        lang_rule = LANG_RULES.get(lang, LANG_RULES["en"])
        content = AGENTS_MD_TEMPLATE.format(
            language_rule=lang_rule,
            role_table=role_table,
        )

        if not dry_run:
            agent_md_path.write_text(content, encoding="utf-8")
            result["created"].append(str(agent_md_path))

    # ── Step 2: Generate role definitions ──
    preset = ROLE_PRESETS.get(project_type, ROLE_PRESETS["software"])
    for rid in roles:
        if rid not in preset:
            continue
        rdata = preset[rid]
        role_path = agents_dir / "roles" / f"{rid}.md"
        if role_path.exists() and not dry_run:
            result["skipped"].append(str(role_path))
            continue
        role_dir = agents_dir / "roles"
        if not dry_run:
            role_dir.mkdir(parents=True, exist_ok=True)
            role_path.write_text(
                ROLE_DEFINITION_TEMPLATE.format(**rdata),
                encoding="utf-8",
            )
            result["created"].append(str(role_path))

    # ── Step 3: Generate .gitignore ──
    gi_path = target_dir / ".gitignore"
    if not gi_path.exists() and not dry_run:
        gi_path.write_text(GITIGNORE_TEMPLATE, encoding="utf-8")
        result["created"].append(str(gi_path))

    return result


# ── 主流程 ──────────────────────────────────────────────────

def main() -> int:
    parser = argparse.ArgumentParser(
        description="泛化引擎 CLI —— 从规范体系模板生成新项目骨架",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    # init 子命令
    init_parser = subparsers.add_parser("init", help="初始化新项目")
    init_parser.add_argument("--name", type=str, default=None, help="项目名称")
    init_parser.add_argument(
        "--type", type=str, default="software",
        choices=["software", "library"],
        help="项目类型",
    )
    init_parser.add_argument(
        "--lang", type=str, default="zh",
        choices=["zh", "en"],
        help="主语言",
    )
    init_parser.add_argument(
        "--roles", type=str, default=None,
        help="角色列表（逗号分隔，如 developer,reviewer,architect）",
    )
    init_parser.add_argument(
        "--output", "-o", type=str, default=None,
        help="目标目录（默认为当前目录）",
    )
    init_parser.add_argument(
        "--dry-run", action="store_true",
        help="仅预览，不生成文件",
    )
    init_parser.add_argument(
        "--force", "-f", action="store_true",
        help="覆盖已存在的文件",
    )

    args = parser.parse_args()

    if args.command != "init":
        print(f"未知命令: {args.command}", file=sys.stderr)
        return 1

    # 交互式补充
    name = args.name
    if not name:
        name = input("项目名称: ").strip()
        if not name:
            print("错误: 项目名称不能为空", file=sys.stderr)
            return 1

    project_type = args.type
    lang = args.lang
    roles_str = args.roles
    if not roles_str:
        defaults = "developer,reviewer" if project_type == "library" else "developer,reviewer,architect,orchestrator,tester"
        roles_str = input(f"角色列表（逗号分隔，回车=默认 {defaults}）: ").strip()
        if not roles_str:
            roles_str = defaults
    roles = [r.strip() for r in roles_str.split(",")]

    target_dir = Path(args.output) if args.output else Path.cwd()

    dry_run = args.dry_run
    if dry_run:
        print_header(f"预览模式：{name} ({project_type}, {lang})")
        print(f"目标目录: {target_dir}")
        print(f"角色: {', '.join(roles)}")
        print()

    result = generate_project(target_dir, name, project_type, lang, roles, dry_run=dry_run)

    if not dry_run:
        print_header(f"项目初始化完成: {name}")
        print()
        if result["created"]:
            print("已创建:")
            for f in result["created"]:
                print_pass(f"创建 {Path(f).name}")
        if result["skipped"]:
            print("已跳过 (文件已存在):")
            for f in result["skipped"]:
                print_warn(f"跳过 {Path(f).name}")
        print()
        print_summary(len(result["created"]), len(result["skipped"]), len(result["errors"]))
        print()
        print("下一步:")
        print(f"  cd {target_dir}")
        print("  编辑 AGENTS.md 补全项目信息")
        print("  编辑 .agents/roles/*.md 调整角色职责")
        print("  运行 .agents/scripts/check-gitignore.py 验证")

    return 1 if result["errors"] else 0


if __name__ == "__main__":
    sys.exit(main())

