"""Tests for scripts/verify_working_leo_apply_readiness.py."""

from __future__ import annotations

import json
import shutil
import sys
from pathlib import Path

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

import verify_working_leo_apply_readiness as readiness  # noqa: E402


def _copy_readiness_fixture(tmp_path: Path) -> Path:
    source_dir = REPO_ROOT / readiness.REPO_REPORT_DIR
    fixture_dir = tmp_path / "reports"
    fixture_dir.mkdir()
    manifest = json.loads((source_dir / "working-leo-integrated-packet.json").read_text())
    files = {
        "working-leo-integrated-packet.json",
        readiness.CLONE_LOG,
        readiness.CLONE_REPORT,
    }
    for packet in manifest["packets"]:
        files.add(packet["apply_sql"])
        files.add(packet["rollback_sql"])
        files.add(packet["packet_json"])
    for filename in files:
        shutil.copy2(source_dir / filename, fixture_dir / filename)
    return fixture_dir


def test_readiness_passes_current_retained_artifacts():
    result = readiness.build_readiness()
    assert result["ready_for_authorized_production_apply_packet"] is True
    assert result["production_apply_executed"] is False
    assert result["production_apply_authorization_present"] is False
    assert all(result["checks"].values())
    assert result["missing_apply_markers"] == []
    assert result["missing_rollback_markers"] == []


def test_readiness_fails_if_manifest_says_executed(tmp_path: Path):
    fixture_dir = _copy_readiness_fixture(tmp_path)
    manifest_path = fixture_dir / "working-leo-integrated-packet.json"
    manifest = json.loads(manifest_path.read_text())
    manifest["production_apply_status"] = "executed"
    manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")

    result = readiness.build_readiness(fixture_dir)

    assert result["ready_for_authorized_production_apply_packet"] is False
    assert result["checks"]["manifest_status_not_executed"] is False
    assert result["checks"]["all_packet_files_ok"] is True


def test_markdown_report_keeps_authorization_boundary(tmp_path: Path):
    result = readiness.build_readiness()
    out = tmp_path / "readiness.md"

    readiness.write_markdown_report(out, result)

    text = out.read_text()
    assert "Ready for separately authorized production apply packet: `True`" in text
    assert "Production apply executed: `False`" in text
    assert "It does not authorize or prove production DB mutation." in text
