"""Tests for scripts/kb_cross_surface_resolution_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 kb_cross_surface_resolution_packet as packet  # noqa: E402


def test_packet_declares_only_strategy_anchor_safe_write():
    result = packet.build_packet()
    assert result["base_packet_required_first"] == "production-apply-packet-mapped-20260709"
    assert result["safe_writes"] == [
        {
            "table": "public.strategy_node_anchors",
            "operation": "update",
            "id": packet.ANCHOR_ID,
            "from_node_id": packet.POLICY_NODE_ID,
            "from_node_title": packet.POLICY_NODE_TITLE,
            "old_claim_id": packet.OLD_INTERNET_FINANCE_CLAIM_ID,
            "new_claim_id": packet.CLAIM_D_ID,
            "approval_source_id": packet.APPROVAL_SOURCE_ID,
            "reason": "Replace the active Leo policy anchor that points at the retiring compressed internet-finance claim with the approved Claim D boundary claim.",
        }
    ]
    targets = {item["target"]: item for item in result["known_non_writable_targets"]}
    assert targets["governance_gate:quality-gate"]["existing_row_id"] == packet.QUALITY_GATE_ID
    assert targets["governance_gate:evidence-bar"]["existing_row_id"] == packet.EVIDENCE_BAR_ID
    assert targets["concept_map:distributed_market_intelligence"]["existing_row_id"] is None


def test_apply_sql_is_guarded_on_base_rows_and_old_anchor_state():
    sql = packet.build_packet()["sql"]["apply_commit"]
    assert "requires Claim D" in sql
    assert "requires approval source" in sql
    assert f"id = '{packet.ANCHOR_ID}'::uuid" in sql
    assert f"claim_id = '{packet.OLD_INTERNET_FINANCE_CLAIM_ID}'::uuid" in sql
    assert f"set claim_id = '{packet.CLAIM_D_ID}'::uuid" in sql
    assert f"source_id = '{packet.APPROVAL_SOURCE_ID}'::uuid" not in sql
    assert "expected 1; anchor was not at old claim state" in sql
    assert sql.strip().endswith("commit;")


def test_rollback_restores_old_anchor_state():
    sql = packet.build_packet()["sql"]["delete_rollback"]
    assert f"set claim_id = '{packet.OLD_INTERNET_FINANCE_CLAIM_ID}'::uuid" in sql
    assert "source_id = null" in sql
    assert "weight = 0.7" in sql
    assert f"and claim_id = '{packet.CLAIM_D_ID}'::uuid" in sql
    assert "expected 1; anchor was not at Claim D state" in sql


def test_write_packet_files(tmp_path: Path):
    result = packet.build_packet()
    packet.write_packet_files(result, tmp_path)
    expected = {
        "cross-surface-preflight.sql",
        "cross-surface-apply-rollback-rehearsal.sql",
        "cross-surface-apply-authorized-commit.sql",
        "cross-surface-postflight.sql",
        "cross-surface-delete-rollback.sql",
        "cross-surface-packet.json",
    }
    assert {path.name for path in tmp_path.iterdir()} == expected
    summary = json.loads((tmp_path / "cross-surface-packet.json").read_text())
    assert "sql" not in summary
    assert summary["production_apply_status"] == "not_executed"
