"""tests/dev7/test_auto_revert.py — auto revert PR 생성 (task-2367 P1)"""
# pyright: reportAttributeAccessIssue=false
import json
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))


@pytest.fixture
def revert_workspace(tmp_path, monkeypatch):
    (tmp_path / "memory" / "events").mkdir(parents=True)
    (tmp_path / "memory" / "audit").mkdir(parents=True)
    monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
    import importlib.util
    spec = importlib.util.spec_from_file_location(
        "auto_revert",
        str(Path(__file__).resolve().parents[2] / "scripts" / "auto_revert.py"),
    )
    assert spec is not None and spec.loader is not None
    ar = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(ar)
    ar.WORKSPACE = tmp_path
    ar.AUDIT_LOG = tmp_path / "memory" / "audit" / "auto-merge.log"
    return tmp_path, ar


def test_revert_uses_git_revert_not_reset(revert_workspace, tmp_path, monkeypatch):
    """★ 가장 중요: hard reset 사용 X, git revert -m 1 사용."""
    workspace, ar = revert_workspace
    project = tmp_path / "fake_project"
    project.mkdir()

    # subprocess 추적
    captured_calls = []
    def _fake_check_call(args, **kw):
        captured_calls.append(args)
        return 0
    def _fake_run(args, **kw):
        captured_calls.append(args)
        class R:
            returncode = 0
            stdout = "https://example.com/pr/1\n"
            stderr = ""
        return R()
    monkeypatch.setattr(ar.subprocess, "check_call", _fake_check_call)
    monkeypatch.setattr(ar.subprocess, "run", _fake_run)

    result = ar.create_revert_pr(
        task_id="task-revert-test",
        merge_sha="deadbeef0000",
        project_path=project,
        reason="test",
    )

    # 모든 git 호출에서 reset --hard 0건
    all_args_flat = " ".join(" ".join(a) if isinstance(a, list) else str(a) for a in captured_calls)
    assert "reset --hard" not in all_args_flat
    assert "reset" not in all_args_flat or "--hard" not in all_args_flat

    # git revert -m 1 호출 확인
    revert_calls = [c for c in captured_calls if isinstance(c, list) and "revert" in c]
    assert len(revert_calls) >= 1
    assert "-m" in revert_calls[0]
    assert "1" in revert_calls[0]
    assert "deadbeef0000" in revert_calls[0]

    # audit 기록
    assert result["outcome"] == "reverted"
    assert result["revert"]["branch"] == "revert/task-revert-test"
    assert "pr_url" in result["revert"]

    log = workspace / "memory" / "audit" / "auto-merge.log"
    assert log.exists()


def test_revert_audit_includes_reason(revert_workspace, tmp_path, monkeypatch):
    """audit 기록에 reason 포함."""
    workspace, ar = revert_workspace
    project = tmp_path / "p"
    project.mkdir()

    monkeypatch.setattr(ar.subprocess, "check_call", lambda *a, **kw: 0)
    class R:
        returncode = 0
        stdout = ""
        stderr = ""
    monkeypatch.setattr(ar.subprocess, "run", lambda *a, **kw: R())

    result = ar.create_revert_pr(
        task_id="t1",
        merge_sha="abc",
        project_path=project,
        reason="probe FAIL: build OK test FAIL",
    )
    log = workspace / "memory" / "audit" / "auto-merge.log"
    line = log.read_text().strip().split("\n")[0]
    record = json.loads(line)
    assert "probe FAIL" in record["revert"]["reason"]
