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


def test_stable_ids_are_deterministic():
    assert packet.stable_id("strategy-node:rio-capital-deployment-layer") == packet.CAPITAL_LAYER_NODE_ID
    assert (
        packet.stable_id("strategy-node:rio-internet-finance-capital-product")
        == packet.INTERNET_FINANCE_PRODUCT_NODE_ID
    )
    assert packet.CAPITAL_LAYER_NODE_ID != packet.INTERNET_FINANCE_PRODUCT_NODE_ID


def test_packet_declares_rio_nodes_and_anchors_only():
    result = packet.build_packet()
    assert result["base_packet_required_first"] == "production-apply-packet-mapped-20260709"
    assert result["production_apply_status"] == "not_executed"
    assert result["generated_counts"] == {"strategy_node_anchors": 5, "strategy_nodes": 2}
    assert result["required_existing_rows"] == {
        "public.agents": [packet.RIO_AGENT_ID],
        "public.claims": [packet.CLAIM_A_ID, packet.CLAIM_C_ID, packet.CLAIM_D_ID],
        "public.shared_root": [packet.BACK_SHARED_ROOT_ID],
    }

    writes = {item["table"]: item for item in result["safe_writes"]}
    assert set(writes) == {"public.strategy_node_anchors", "public.strategy_nodes"}
    assert len(writes["public.strategy_nodes"]["rows"]) == 2
    assert len(writes["public.strategy_node_anchors"]["rows"]) == 5

    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_anchor_contract_represents_rio_strategy_fragments():
    anchors = {row["id"]: row for row in packet.strategy_anchors()}
    assert anchors[packet.CAPITAL_JUSTIFIED_BY_CLAIM_A_ANCHOR_ID]["claim_id"] == packet.CLAIM_A_ID
    assert anchors[packet.CAPITAL_SERVES_BACK_ANCHOR_ID]["to_shared_root_id"] == packet.BACK_SHARED_ROOT_ID
    assert anchors[packet.PRODUCT_JUSTIFIED_BY_CLAIM_C_ANCHOR_ID]["claim_id"] == packet.CLAIM_C_ID
    assert anchors[packet.PRODUCT_JUSTIFIED_BY_CLAIM_D_ANCHOR_ID]["claim_id"] == packet.CLAIM_D_ID
    assert anchors[packet.PRODUCT_SERVES_CAPITAL_LAYER_ANCHOR_ID]["to_node_id"] == packet.CAPITAL_LAYER_NODE_ID
    assert all(row["anchor_role"] in {"justified_by", "serves"} for row in anchors.values())


def test_apply_sql_is_guarded_on_base_rows_duplicates_and_counts():
    sql = packet.build_packet()["sql"]["apply_commit"]
    assert "requires mapped base claims A/C/D" in sql
    assert f"id = '{packet.RIO_AGENT_ID}'::uuid and handle = 'rio'" in sql
    assert f"where id = '{packet.BACK_SHARED_ROOT_ID}'::uuid" in sql
    assert "generated strategy node id already exists" in sql
    assert "generated strategy anchor id already exists" in sql
    assert "duplicate exact Rio strategy title" in sql
    assert "expected 2" in sql
    assert "expected 5" in sql
    assert sql.strip().endswith("commit;")


def test_rollback_sql_deletes_anchors_before_nodes_and_guards_counts():
    sql = packet.build_packet()["sql"]["delete_rollback"]
    anchor_delete = sql.index("delete from public.strategy_node_anchors")
    node_delete = sql.index("delete from public.strategy_nodes")
    assert anchor_delete < node_delete
    assert "expected 5" in sql
    assert "expected 2" in sql
    assert sql.strip().endswith("commit;")


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