from __future__ import annotations

from pathlib import Path

from typer.testing import CliRunner

from zsc.cli import app


runner = CliRunner()


def _write_task_md(path: Path, title: str, completed: bool) -> None:
    status_block = (
        "> 只维护最新版本；完成后清空 TODO，仅保留\"完成记录 + 日期\"。\n"
        "- （本轮已完成，TODO 清空）\n"
    )
    todos = "" if completed else "- [ ] TODO item 1\n"
    path.write_text(
        f"# {title}\n\n"
        "## 闭环描述\n\n"
        "...\n\n"
        "## TODO_LIST\n\n"
        f"{status_block}\n"
        f"{todos}",
        encoding="utf-8",
    )


def test_task_list_on_empty_agents(tmp_path: Path) -> None:
    result = runner.invoke(app, ["task", "list", str(tmp_path)])
    assert result.exit_code == 0
    assert "No tasks found" in result.stdout


def test_task_new_creates_task_structure(tmp_path: Path) -> None:
    result = runner.invoke(app, ["task", "new", "demo_feature", str(tmp_path)])
    assert result.exit_code == 0
    # Guidance about using zsc-create-task and LLM limitation should be printed
    assert "zsc-create-task" in result.stdout
    assert "仅负责创建目录与模板" in result.stdout

    task_dir = tmp_path / ".agents" / "tasks" / "task_01_demo_feature"
    assert task_dir.exists()
    assert (task_dir / "task_01_demo_feature.md").exists()
    assert (task_dir / "task_records" / "log").exists()

    # list should now show this task as open (has TODO items)
    list_result = runner.invoke(app, ["task", "list", str(tmp_path)])
    assert list_result.exit_code == 0
    assert "task_01_demo_feature" in list_result.stdout


def test_task_status_counts_completed_and_open(tmp_path: Path) -> None:
    tasks_root = tmp_path / ".agents" / "tasks"
    (tasks_root / "task_01_a").mkdir(parents=True)
    (tasks_root / "task_02_b").mkdir(parents=True)

    _write_task_md(tasks_root / "task_01_a" / "task_01_a.md", "Task 01: A", completed=True)
    _write_task_md(tasks_root / "task_02_b" / "task_02_b.md", "Task 02: B", completed=False)

    result = runner.invoke(app, ["task", "status", str(tmp_path)])
    assert result.exit_code == 0
    # basic sanity checks on counts
    assert "total:" in result.stdout
    assert "completed: 1" in result.stdout
    assert "open:      1" in result.stdout


def test_parse_task_md_prefers_named_md_fallback_to_task_md(tmp_path: Path) -> None:
    """Legacy task.md is still read when task_dir_name.md does not exist."""
    tasks_root = tmp_path / ".agents" / "tasks"
    tasks_root.mkdir(parents=True)
    (tasks_root / "task_01_legacy").mkdir()
    _write_task_md(tasks_root / "task_01_legacy" / "task.md", "Task 01: Legacy", completed=True)
    result = runner.invoke(app, ["task", "list", str(tmp_path)])
    assert result.exit_code == 0
    assert "task_01_legacy" in result.stdout
    assert "completed" in result.stdout


def test_root_without_args_shows_purpose_and_usage() -> None:
    result = runner.invoke(app, [])
    assert result.exit_code == 0
    assert "zsc: 初始化并管理基于 .agents/tasks 的 AI Agents 任务体系。" in result.stdout
    assert "zsc init ." in result.stdout
    assert "zsc task list" in result.stdout

