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

from pathlib import Path
import sys

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

import kb_proposal_review_packet as rp  # 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"]
