"""끝날 때의 검증은 방금 만든 결과를 본다 — 옛 CP 를 읽으면 이번 판이 partial 로 접힌다 (실측 2026-09-03)."""
from __future__ import annotations

from app.core.steps.reference_acquisition_step import ReferenceAcquisitionStep as S
from app.modules.pipeline import grounding_central_acquisition as ca


def _row(final_id, status, cands):
    return {"disposition": ca.DISP_ACQUIRED, "status": status,
            "ledger_row": {"final_id": final_id},
            "acquisition": {"status": status, "chosen": None,
                            "rounds": [{"round_no": 1, "downloaded_candidates": cands}]}}


def _step(monkeypatch, last, cp_rows):
    s = S.__new__(S)
    s.project_id, s.episode_id, s.db = "p", "e", None
    s._last_execute_result = last
    monkeypatch.setattr(s, "_load_prev_checkpoint", lambda sid: {"data": {"rows": cp_rows}}, raising=False)
    return s


def test_exit_verify_uses_the_fresh_result_not_the_stale_checkpoint(monkeypatch):
    stale = [_row("A", "retryable", [{"index": 1}])]              # 옛 CP: 미판정 1
    fresh = {"data": {"rows": [_row("A", "no_match_after_retry", [{"index": 1}])]}}   # 이번 결과: 끝남
    assert _step(monkeypatch, fresh, stale).verify_completion().is_complete is True


def test_resume_verify_reads_the_checkpoint_when_there_is_no_fresh_result(monkeypatch):
    stale = [_row("A", "retryable", [{"index": 1}])]
    got = _step(monkeypatch, None, stale).verify_completion()
    assert got.is_complete is False and got.metadata["rejudge_pending"] == 1
