from __future__ import annotations

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from chekan.gates import _zones_overlap, _zone_conflicts
from chekan.store import Run


def test_zones_overlap() -> None:
    assert _zones_overlap("src/bot/", "src/bot/") is True
    assert _zones_overlap("src/bot/", "src/bot/handlers/") is True
    assert _zones_overlap("src/bot/handlers", "src/bot") is True
    assert _zones_overlap("src/bot", "src/api") is False
    assert _zones_overlap("", "src/bot") is False


def test_zone_conflicts_hierarchical() -> None:
    tasks = [
        {"id": "01", "zone": "app/src/", "deps": []},
        {"id": "02", "zone": "app/src/main/java/", "deps": []},
    ]
    conflicts = _zone_conflicts(tasks)
    assert len(conflicts) == 1
    assert "01" in conflicts[0] and "02" in conflicts[0]

    # With dependency, conflict is resolved
    tasks_with_dep = [
        {"id": "01", "zone": "app/src/", "deps": []},
        {"id": "02", "zone": "app/src/main/java/", "deps": ["01"]},
    ]
    assert len(_zone_conflicts(tasks_with_dep)) == 0


def test_task_reset(tmp_path: Path, monkeypatch, capsys) -> None:
    from chekan.__main__ import build_parser

    run = Run.create(tmp_path, "Тест сброса таска", "auto", "T1")
    run.add_requirement("R01", "требование", "заметка")
    run.add_task("01", "Задача 01", ["R01"], zone="src/")
    run.set_task_status("01", "in-progress")
    assert run.task("01")["status"] == "in-progress"

    monkeypatch.chdir(tmp_path)
    parser = build_parser()
    args = parser.parse_args(["task", "reset", "01"])
    res = args.func(args)
    captured = capsys.readouterr()

    assert res == 0
    assert "таск 01 сброшен в pending" in captured.out
    assert Run.load(tmp_path).task("01")["status"] == "pending"
