"""
test_enqueue_merge.py — enqueue_pr dry_run 회귀 테스트.

- bot author + human APPROVED → DRY_RUN outcome, audit jsonl +1, mergeable=MERGEABLE
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest

# worktree 루트를 sys.path에 추가
_WORKTREE_ROOT = str(Path(__file__).resolve().parents[2])
if _WORKTREE_ROOT not in sys.path:
    sys.path.insert(0, _WORKTREE_ROOT)


def test_enqueue_merge_dry_run_audit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    """enqueue_pr(99, dry_run=True) + bot author + human APPROVED → DRY_RUN + audit jsonl +1."""
    monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
    monkeypatch.setenv("TASKCTL_TEST_MODE", "1")
    monkeypatch.setenv("TASKCTL_PR_AUTHOR_OVERRIDE", "jeon-jonghyuk-taskctl-bot[bot]")
    monkeypatch.setenv(
        "TASKCTL_PR_REVIEWS_OVERRIDE",
        json.dumps([{"author": {"login": "jonghyuk-jeon"}, "state": "APPROVED"}]),
    )

    # utils.merge_queue_client을 새로 로드 (WORKSPACE_ROOT 반영)
    monkeypatch.delitem(sys.modules, "utils.merge_queue_client", raising=False)
    # bot_pr_author도 재로드
    monkeypatch.delitem(sys.modules, "utils.bot_pr_author", raising=False)

    import utils.merge_queue_client as mqc  # type: ignore[import-not-found]

    log_path = tmp_path / "memory" / "orchestration-audit" / "merge-queue.jsonl"
    monkeypatch.setattr(mqc, "WORKSPACE", tmp_path)
    monkeypatch.setattr(mqc, "MERGE_QUEUE_LOG", log_path)

    # 호출 전 라인 수
    lines_before = 0
    if log_path.exists():
        lines_before = len(log_path.read_text(encoding="utf-8").strip().splitlines())

    result = mqc.enqueue_pr(99, no_admin_override=True, dry_run=True)

    # outcome=DRY_RUN 검증
    assert result["outcome"] == "DRY_RUN", f"expected DRY_RUN, got: {result['outcome']}"

    # audit_entry 검증
    audit_entry = result.get("audit_entry", {})
    assert audit_entry.get("mergeable") == "MERGEABLE", (
        f"mergeable mismatch: {audit_entry.get('mergeable')}"
    )
    assert audit_entry.get("reviewer") == "jonghyuk-jeon", (
        f"reviewer mismatch: {audit_entry.get('reviewer')}"
    )

    # MERGE_QUEUE_LOG 라인 +1 확인
    assert log_path.exists(), f"MERGE_QUEUE_LOG not created: {log_path}"
    lines_after = len(log_path.read_text(encoding="utf-8").strip().splitlines())
    assert lines_after == lines_before + 1, (
        f"expected {lines_before + 1} lines, got {lines_after}"
    )

    # jsonl 마지막 항목 상세 검증
    last_line = log_path.read_text(encoding="utf-8").strip().splitlines()[-1]
    entry = json.loads(last_line)
    assert entry["outcome"] == "DRY_RUN"
    assert entry["dry_run"] is True
    assert entry["pr_number"] == 99
    assert entry["reviewer"] == "jonghyuk-jeon"
    assert entry["mergeable"] == "MERGEABLE"
