"""Tests for scripts/kb_proposal_review_packet.py."""

import copy
import sys
from pathlib import Path

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

import kb_proposal_review_packet as rp  # noqa: E402

from tests import test_compile_kb_source_packet as source_compiler_fixture  # noqa: E402


def test_approved_freeform_packet_is_not_worker_applyable():
    proposal = {
        "id": "14fa5ecc-ac7a-41c1-807d-a2e85b936617",
        "proposal_type": "attach_evidence",
        "status": "approved",
        "reviewed_by_handle": "m3ta",
        "payload": {
            "proposal_kind": "supersede_compressed_claim_with_split_claim_cluster",
            "old_claim": {"id": "d0000000-0000-0000-0000-000000000005"},
            "claim_candidates": [{"headline": "A"}, {"headline": "B"}],
            "source_candidates": [{"source_key": "hayek"}],
            "proposed_supersession_edges": [{"edge_type": "supersedes_component_of"}],
            "proposed_concept_map_dependency": {"headline": "Distributed market intelligence"},
            "schema_gap_note": "bridge cannot propose claims directly",
        },
    }

    packet = rp.classify_proposal(proposal)

    assert packet["review_state"] == "approved_needs_apply_payload"
    assert packet["worker_applyable"] is False
    assert packet["has_apply_payload"] is False
    assert "strict payload.apply_payload" in packet["applyability"]["missing_contract"]
    assert "claim-row normalization" in packet["applyability"]["missing_contract"]
    assert packet["payload_summary"]["claim_candidate_count"] == 2
    assert packet["payload_summary"]["has_concept_map_dependency"] is True
    assert "normalize into one or more strict apply_payload" in packet["next_admin_action"]


def test_approved_strict_packet_is_worker_applyable():
    proposal = {
        "id": "edge-proposal",
        "proposal_type": "add_edge",
        "status": "approved",
        "payload": {
            "apply_payload": {
                "from_claim": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
                "to_claim": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
                "edge_type": "supports",
            }
        },
    }

    packet = rp.classify_proposal(proposal)

    assert packet["review_state"] == "approved_applyable"
    assert packet["worker_applyable"] is True
    assert packet["applyability"]["missing_contract"] == []
    assert "Show dry-run SQL" in packet["next_admin_action"]


def test_pending_packet_needs_human_review():
    packet = rp.classify_proposal(
        {
            "id": "pending",
            "proposal_type": "add_edge",
            "status": "pending_review",
            "payload": {"apply_payload": {"from_claim": "a", "to_claim": "b", "edge_type": "supports"}},
        }
    )

    assert packet["review_state"] == "needs_human_review"
    assert packet["worker_applyable"] is False
    assert "approve, reject, or request edits" in packet["next_admin_action"]


def test_v3_source_packet_exposes_exact_rows_normalization_and_hashes(tmp_path: Path):
    bundle = source_compiler_fixture._compile_v3(tmp_path / "source")
    proposal = copy.deepcopy(bundle["strict_child_proposal"])

    packet = rp.classify_proposal(proposal)

    apply_payload = proposal["payload"]["apply_payload"]
    assert packet["review_state"] == "needs_human_review"
    assert packet["payload_summary"]["contract_version"] == 3
    assert packet["payload_summary"]["strict_row_counts"] == {
        "assessments": 1,
        "claims": 1,
        "edges": 0,
        "evidence": 1,
        "reasoning_tools": 0,
        "sources": 1,
    }
    assert packet["strict_review_material"]["rows"]["claims"] == apply_payload["claims"]
    assert packet["strict_review_material"]["rows"]["sources"] == apply_payload["sources"]
    assert packet["strict_review_material"]["rows"]["evidence"] == apply_payload["evidence"]
    assert packet["strict_review_material"]["rows"]["assessments"] == apply_payload["assessments"]
    assert (
        packet["strict_review_material"]["normalization_manifest"]
        == apply_payload["normalization_manifest"]
    )
    assert packet["strict_review_material"]["apply_payload_sha256"] == rp.canonical_sha256(apply_payload)
    assert packet["strict_review_material"]["proposal_payload_sha256"] == rp.canonical_sha256(proposal["payload"])
