# -*- coding: utf-8 -*-
"""
TDD 测试：首次初始化用户目录
验证：新用户首次启动时自动生成 skills/hooks/commands 目录和 mcp.json 模板
"""
import json
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, r'd:\agent cli\abyss\src')

from abyss.config import init_user_dirs


def test_init_creates_all_dirs():
    """首次初始化应创建 skills/hooks/commands 三个子目录"""
    with tempfile.TemporaryDirectory() as tmp:
        base = Path(tmp) / ".abyss"
        init_user_dirs(base)
        assert (base / "skills").is_dir()
        assert (base / "hooks").is_dir()
        assert (base / "commands").is_dir()


def test_init_creates_mcp_json_template():
    """首次初始化应创建 mcp.json 模板，含空 mcp_servers 列表"""
    with tempfile.TemporaryDirectory() as tmp:
        base = Path(tmp) / ".abyss"
        init_user_dirs(base)
        mcp_file = base / "mcp.json"
        assert mcp_file.exists()
        data = json.loads(mcp_file.read_text(encoding="utf-8-sig"))
        assert data == {"mcp_servers": []}


def test_init_creates_readme_hint():
    """首次初始化应在 hooks/ 下创建事件子目录占位"""
    with tempfile.TemporaryDirectory() as tmp:
        base = Path(tmp) / ".abyss"
        init_user_dirs(base)
        assert (base / "hooks" / "PreToolUse").is_dir()
        assert (base / "hooks" / "PostToolUse").is_dir()


def test_init_idempotent_no_overwrite():
    """已存在的 mcp.json 不应被覆盖"""
    with tempfile.TemporaryDirectory() as tmp:
        base = Path(tmp) / ".abyss"
        base.mkdir(parents=True)
        existing = {"mcp_servers": [{"name": "my-server", "transport": "stdio", "command": "python"}]}
        (base / "mcp.json").write_text(json.dumps(existing), encoding="utf-8")
        init_user_dirs(base)
        data = json.loads((base / "mcp.json").read_text(encoding="utf-8-sig"))
        assert data == existing


def test_init_idempotent_dirs_exist():
    """目录已存在时不报错"""
    with tempfile.TemporaryDirectory() as tmp:
        base = Path(tmp) / ".abyss"
        init_user_dirs(base)
        # 二次调用不应抛异常
        init_user_dirs(base)
        assert (base / "skills").is_dir()


if __name__ == "__main__":
    test_init_creates_all_dirs()
    print("  ✓ test_init_creates_all_dirs")
    test_init_creates_mcp_json_template()
    print("  ✓ test_init_creates_mcp_json_template")
    test_init_creates_readme_hint()
    print("  ✓ test_init_creates_readme_hint")
    test_init_idempotent_no_overwrite()
    print("  ✓ test_init_idempotent_no_overwrite")
    test_init_idempotent_dirs_exist()
    print("  ✓ test_init_idempotent_dirs_exist")
    print("OK: 全部通过")
