"""
test_handoff_to_bot.py — handoff_pr_to_bot 회귀 테스트.

1. dry_run=True 시 mapping dict 반환 + HANDOFF_LOG jsonl append
2. dry_run 2회 호출 → jsonl 라인 2개, 1회차 라인 보존(append-only)
"""
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 _fake_pr_view(*args: object, **kwargs: object) -> dict:
    del args, kwargs
    return {
        "author": {"login": "human-user"},
        "headRefName": "feat-x",
        "commits": [{"oid": "abc1"}, {"oid": "def2"}],
    }


def test_handoff_to_bot_dry_run_creates_mapping(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    """dry_run=True 호출 → mapping dict 정확히 반환 + jsonl 1건 append."""
    monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))

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

    import utils.handoff_to_bot as hb  # type: ignore[import-not-found]

    # HANDOFF_LOG 경로를 tmp_path로 재설정
    log_path = tmp_path / "memory" / "orchestration-audit" / "handoff-to-bot.jsonl"
    monkeypatch.setattr(hb, "WORKSPACE", tmp_path)
    monkeypatch.setattr(hb, "HANDOFF_LOG", log_path)

    result = hb.handoff_pr_to_bot(
        42,
        dry_run=True,
        pr_view_func=_fake_pr_view,
    )

    # 반환값 검증
    assert result["original_pr"] == 42
    assert result["original_author"] == "human-user"
    assert result["new_branch"] == "task/handoff-42-bot"
    assert result["dry_run"] is True

    # jsonl 1건 append 확인
    assert log_path.exists(), f"HANDOFF_LOG not created: {log_path}"
    lines = log_path.read_text(encoding="utf-8").strip().splitlines()
    assert len(lines) == 1, f"expected 1 jsonl line, got {len(lines)}"

    entry = json.loads(lines[0])
    assert entry["original_pr"] == 42
    assert entry["original_author"] == "human-user"
    assert entry["new_branch"] == "task/handoff-42-bot"
    assert entry["dry_run"] is True
    # original_commits 매핑 확인
    assert entry["original_commits"] == ["abc1", "def2"], (
        f"original_commits mismatch: {entry['original_commits']}"
    )


def test_handoff_to_bot_audit_jsonl_append_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    """dry_run 2회 호출 → jsonl 2라인, 1회차 라인이 그대로 유지(append-only)."""
    monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))

    monkeypatch.delitem(sys.modules, "utils.handoff_to_bot", raising=False)

    import utils.handoff_to_bot as hb  # type: ignore[import-not-found]

    log_path = tmp_path / "memory" / "orchestration-audit" / "handoff-to-bot.jsonl"
    monkeypatch.setattr(hb, "WORKSPACE", tmp_path)
    monkeypatch.setattr(hb, "HANDOFF_LOG", log_path)

    # 1회차
    hb.handoff_pr_to_bot(42, dry_run=True, pr_view_func=_fake_pr_view)
    lines_after_first = log_path.read_text(encoding="utf-8").strip().splitlines()
    first_line = lines_after_first[0]

    # 2회차
    hb.handoff_pr_to_bot(42, dry_run=True, pr_view_func=_fake_pr_view)
    lines_after_second = log_path.read_text(encoding="utf-8").strip().splitlines()

    assert len(lines_after_second) == 2, (
        f"expected 2 jsonl lines after 2 calls, got {len(lines_after_second)}"
    )
    # 1회차 라인이 변경되지 않았음 (append-only)
    assert lines_after_second[0] == first_line, (
        f"1st line was modified (append-only violation):\n"
        f"  before: {first_line}\n"
        f"  after:  {lines_after_second[0]}"
    )
