"""F4 测试：CLI 工具"""

import json
import os
from pathlib import Path

import pytest

pytestmark = pytest.mark.unit

from src.cli.blackboard import run_blackboard_cli, run_admin_cli
from src.blackboard.operations import Blackboard
from src.blackboard.models import Task


@pytest.fixture
def project_env(tmp_path):
    """创建临时项目环境"""
    project_root = tmp_path / "projects"
    project_root.mkdir()
    os.environ["BLACKBOARD_ROOT"] = str(project_root)

    # Create a test project with DB
    proj_dir = project_root / "test-proj"
    proj_dir.mkdir()
    bb = Blackboard(proj_dir / "blackboard.db")
    bb.create_task(Task(id="t1", title="Existing Task", task_type="coding"))

    yield project_root
    del os.environ["BLACKBOARD_ROOT"]


class TestBlackboardCLI:
    def test_read_all_tasks(self, project_env, capsys):
        rc = run_blackboard_cli(["read", "--project", "test-proj"])
        assert rc == 0
        out = capsys.readouterr().out
        assert "t1" in out

    def test_read_json(self, project_env, capsys):
        rc = run_blackboard_cli(["read", "--project", "test-proj", "--json"])
        assert rc == 0
        out = capsys.readouterr().out
        data = json.loads(out)
        assert len(data) == 1
        assert data[0]["id"] == "t1"

    def test_create_task(self, project_env, capsys):
        rc = run_blackboard_cli([
            "create", "--project", "test-proj",
            "--id", "t2", "--title", "New Task",
            "--task-type", "review", "--priority", "3",
        ])
        assert rc == 0
        assert "Created task: t2" in capsys.readouterr().out

    def test_claim(self, project_env, capsys):
        rc = run_blackboard_cli([
            "claim", "--project", "test-proj",
            "--task-id", "t1", "--agent", "zhangfei-dev",
        ])
        assert rc == 0

    def test_output(self, project_env, capsys):
        # First claim and start
        run_blackboard_cli(["claim", "--project", "test-proj",
                           "--task-id", "t1", "--agent", "a1"])
        rc = run_blackboard_cli([
            "output", "--project", "test-proj",
            "--task-id", "t1", "--agent", "a1",
            "--type", "code", "--title", "main.py",
        ])
        assert rc == 0

    def test_comment(self, project_env, capsys):
        rc = run_blackboard_cli([
            "comment", "--project", "test-proj",
            "--task-id", "t1", "--author", "pangtong",
            "--body", "Good work", "--type", "general",
            "--mentions", "zhangfei-dev,guanyu-dev",
        ])
        assert rc == 0

    def test_decide(self, project_env, capsys):
        rc = run_blackboard_cli([
            "decide", "--project", "test-proj",
            "--task-id", "t1", "--decider", "pangtong",
            "--decision", "Use FastAPI", "--rationale", "Best async support",
        ])
        assert rc == 0

    def test_observe(self, project_env, capsys):
        rc = run_blackboard_cli([
            "observe", "--project", "test-proj",
            "--task-id", "t1", "--observer", "simayi",
            "--body", "Potential issue", "--severity", "warning",
        ])
        assert rc == 0

    def test_review(self, project_env, capsys):
        rc = run_blackboard_cli([
            "review", "--project", "test-proj",
            "--review-id", "rev-1", "--task-id", "t1",
            "--reviewer", "simayi", "--review-type", "output_review",
            "--verdict", "approved", "--summary", "LGTM",
            "--confidence", "0.9",
        ])
        assert rc == 0

    def test_read_nonexistent_task(self, project_env, capsys):
        rc = run_blackboard_cli(["read", "--project", "test-proj", "--task-id", "nope"])
        assert rc == 1

    def test_no_command(self, project_env, capsys):
        rc = run_blackboard_cli([])
        assert rc == 1


class TestAdminCLI:
    def test_project_create(self, tmp_path, capsys):
        project_root = tmp_path / "projects"
        project_root.mkdir()
        os.environ["BLACKBOARD_ROOT"] = str(project_root)
        try:
            rc = run_admin_cli([
                "project-create", "--id", "new-proj",
                "--name", "New Project",
                "--agents", "agent1,agent2",
            ])
            assert rc == 0
            assert (project_root / "new-proj" / "config" / "project.yaml").exists()
        finally:
            del os.environ["BLACKBOARD_ROOT"]

    def test_project_list(self, project_env, capsys):
        rc = run_admin_cli(["project-list"])
        assert rc == 0
        # test-proj is not in registry (created manually), so empty output is fine

    def test_no_command(self, project_env, capsys):
        rc = run_admin_cli([])
        assert rc == 1
