# pyright: reportMissingImports=false
"""3-decision classifier: PASS / HOLD_FOR_CHAIR / BLOCK."""
from __future__ import annotations

import subprocess
from pathlib import Path

from utils.main_conflict_preflight import classify_decision, run_preflight


def _git(cwd: Path, *args: str) -> None:
    subprocess.run(
        ["git", *args],
        cwd=str(cwd),
        check=True,
        capture_output=True,
        text=True,
    )


def _init_repo(path: Path) -> None:
    path.mkdir(parents=True, exist_ok=True)
    _git(path, "init", "-q", "-b", "main")
    _git(path, "config", "user.email", "test@example.com")
    _git(path, "config", "user.name", "Test")
    (path / "seed.txt").write_text("seed\n")
    _git(path, "add", "seed.txt")
    _git(path, "commit", "-q", "-m", "seed")


def test_pass_when_main_is_clean(tmp_path: Path) -> None:
    main_ws = tmp_path / "main_ws"
    worktree = tmp_path / "worktree"
    _init_repo(main_ws)
    _init_repo(worktree)

    # main clean, worktree clean
    result = run_preflight(str(worktree), str(main_ws))
    assert result["main_dirty"] == []
    assert result["intersection"] == []
    assert result["violation"] is False
    assert classify_decision(result) == "PASS"


def test_hold_for_chair_when_main_dirty_no_intersection(tmp_path: Path) -> None:
    main_ws = tmp_path / "main_ws"
    worktree = tmp_path / "worktree"
    _init_repo(main_ws)
    _init_repo(worktree)

    # Disjoint dirty files
    (main_ws / "only_in_main.py").write_text("dirty\n")
    (worktree / "only_in_worktree.py").write_text("dirty\n")

    result = run_preflight(str(worktree), str(main_ws))
    assert len(result["main_dirty"]) >= 1
    assert result["intersection"] == []
    assert result["violation"] is False
    assert classify_decision(result) == "HOLD_FOR_CHAIR"


def test_block_when_intersection_non_empty(tmp_path: Path) -> None:
    main_ws = tmp_path / "main_ws"
    worktree = tmp_path / "worktree"
    _init_repo(main_ws)
    _init_repo(worktree)

    (main_ws / "shared.py").write_text("dirty in main\n")
    (worktree / "shared.py").write_text("dirty in worktree\n")

    result = run_preflight(str(worktree), str(main_ws))
    assert "shared.py" in result["intersection"]
    assert result["violation"] is True
    assert classify_decision(result) == "BLOCK"


def test_classify_decision_pure_function_pass():
    assert classify_decision({"main_dirty": [], "intersection": []}) == "PASS"


def test_classify_decision_pure_function_hold():
    assert (
        classify_decision({"main_dirty": ["a.py"], "intersection": []})
        == "HOLD_FOR_CHAIR"
    )


def test_classify_decision_pure_function_block():
    assert (
        classify_decision({"main_dirty": ["a.py"], "intersection": ["a.py"]})
        == "BLOCK"
    )
