"""Tests for scripts/working_leo_integrated_packet.py."""

from __future__ import annotations

import json
import sys
from pathlib import Path

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

import working_leo_integrated_packet as packet  # noqa: E402


def test_manifest_apply_and_rollback_order():
    result = packet.build_manifest()
    assert result["production_apply_status"] == "not_executed"
    assert result["apply_order"] == [
        "mapped-rich-base",
        "cross-surface-anchor",
        "rio-strategy-context",
        "governance-concept-schema",
        "helmer-7powers",
    ]
    assert result["rollback_order"] == [
        "helmer-7powers",
        "governance-concept-schema",
        "rio-strategy-context",
        "cross-surface-anchor",
        "mapped-rich-base",
    ]


def test_manifest_expected_counts_are_composed_from_packets():
    result = packet.build_manifest()
    assert result["expected_after_apply_counts"] == {
        "claim_concept_map_links": 1,
        "claim_edges": 18,
        "claim_evidence": 34,
        "claim_governance_gate_links": 2,
        "claims": 12,
        "concept_maps": 1,
        "cross_surface_anchor_updates": 1,
        "helmer_ledger_rows_marked_applied": 1,
        "reasoning_tools": 1,
        "rio_strategy_anchors": 5,
        "rio_strategy_nodes": 2,
        "sources": 28,
    }


def test_manifest_packet_files_exist_and_are_relative_to_report_dir():
    result = packet.build_manifest()
    report_dir = Path(result["report_dir"])
    for item in result["packets"]:
        assert (report_dir / item["apply_sql"]).exists()
        assert (report_dir / item["rollback_sql"]).exists()
        assert (report_dir / item["packet_json"]).exists()
        assert not Path(item["apply_sql"]).is_absolute()


def test_write_manifest_files(tmp_path: Path):
    result = packet.build_manifest()
    packet.write_manifest_files(result, tmp_path)
    written_json = json.loads((tmp_path / "working-leo-integrated-packet.json").read_text())
    written_md = (tmp_path / "working-leo-integrated-packet.md").read_text()
    assert written_json["apply_order"][0] == "mapped-rich-base"
    assert "## Apply Order" in written_md
    assert "`claims`: `12`" in written_md
