#!/usr/bin/env python3
"""Validate PRISM-SCREENPLAY-IR-1.0 craft, attention, dialogue and runtime gates."""

from __future__ import annotations

import argparse
import json
import math
import sys
from pathlib import Path
from typing import Any

try:
    import yaml
except ImportError:  # pragma: no cover
    yaml = None


SCHEMA = "PRISM-SCREENPLAY-IR-1.0"
ROOT_KEYS = {
    "schema_version", "runtime_context", "source_contract", "craft_policy",
    "voiceprints", "structural_assets", "scenes", "runtime_budget", "layer_receipt",
}
PRIMARY_FUNCTIONS = {"ORIENT", "PRESSURE", "ACTION", "REACTION", "REVEAL", "DECISION", "PAYOFF", "RESIDUE"}
TURN_TYPES = {"REVERSAL", "DISCOVERY", "COMPLICATION", "DECISION", "REDEFINED_GOAL", "PAYOFF", "NONE"}
PRESSURE_MODES = {
    "CLOCK", "EXPOSURE", "RESOURCE_DEPLETION", "NARROWING_OPTIONS", "PHYSICAL_DANGER",
    "RELATIONSHIP_RUPTURE", "MORAL_DILEMMA", "INFORMATION_GAP",
}
OBSERVABILITY = {"VISIBLE", "AUDIBLE", "PERFORMANCE_INFERENCE"}
REFERENT_STATUSES = {"CLEAR", "INTENTIONAL_AMBIGUITY", "NOT_APPLICABLE"}
TRUTH_MODES = {"LITERAL", "LIE", "HALF_TRUTH", "EVASION", "CODED", "UNKNOWN"}
IMAGE_RELATIONS = {"ADD", "REFRAME", "CONTRADICT", "COMMAND", "WITHHOLD", "DUPLICATE"}
RESPONSE_TYPES = {"ANSWER", "EVADE", "REFUSE", "COUNTER", "REFRAME", "INTERRUPT", "IGNORE_WITH_EVIDENCE", "ACTION_RESPONSE"}
HANDOFFS = {"NONE_FIRST", "DIRECT_CONTINUITY", "VISIBLE_TRANSFER", "OFFSCREEN_TRANSFER", "TIME_JUMP"}


def load_document(path: Path) -> dict[str, Any]:
    text = path.read_text(encoding="utf-8")
    if path.suffix.lower() == ".json":
        data = json.loads(text)
    else:
        if yaml is None:
            raise RuntimeError("PyYAML is required for YAML input; use JSON instead")
        data = yaml.safe_load(text)
    if not isinstance(data, dict):
        raise ValueError("root must be an object")
    return data


def numeric(value: Any) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def required(mapping: Any, keys: list[str], prefix: str, errors: list[str]) -> None:
    if not isinstance(mapping, dict):
        errors.append(f"{prefix}: must be an object")
        return
    for key in keys:
        if mapping.get(key) in (None, "", [], {}):
            errors.append(f"{prefix}: missing {key}")


def validate_runtime_budget(budget: Any, prefix: str, errors: list[str]) -> None:
    required(
        budget,
        [
            "allocated_seconds", "spoken_seconds", "action_comprehension_seconds",
            "reaction_and_silence_seconds", "transition_or_reorientation_seconds",
            "overlap_seconds", "estimated_occupied_seconds", "reserve_seconds", "test_method",
        ],
        prefix,
        errors,
    )
    if not isinstance(budget, dict):
        return
    number_keys = [
        "allocated_seconds", "spoken_seconds", "action_comprehension_seconds",
        "reaction_and_silence_seconds", "transition_or_reorientation_seconds",
        "overlap_seconds", "estimated_occupied_seconds", "reserve_seconds",
    ]
    if any(not numeric(budget.get(key)) or float(budget.get(key)) < 0 for key in number_keys):
        errors.append(f"{prefix}: duration fields must be non-negative finite numbers")
        return
    expected = (
        float(budget["spoken_seconds"])
        + float(budget["action_comprehension_seconds"])
        + float(budget["reaction_and_silence_seconds"])
        + float(budget["transition_or_reorientation_seconds"])
        - float(budget["overlap_seconds"])
    )
    if abs(expected - float(budget["estimated_occupied_seconds"])) > 0.2:
        errors.append(f"{prefix}: estimated occupied time does not match component budget")
    if float(budget["estimated_occupied_seconds"]) > float(budget["allocated_seconds"]) + 0.2:
        errors.append(f"{prefix}: estimated occupied time exceeds allocated scene duration")
    expected_reserve = float(budget["allocated_seconds"]) - float(budget["estimated_occupied_seconds"])
    if abs(expected_reserve - float(budget["reserve_seconds"])) > 0.2:
        errors.append(f"{prefix}: reserve_seconds must equal allocated minus occupied")


def validate(data: dict[str, Any]) -> tuple[list[str], list[str]]:
    errors: list[str] = []
    warnings: list[str] = []

    if data.get("schema_version") != SCHEMA:
        errors.append(f"schema_version must be {SCHEMA}")
    unknown = set(data) - ROOT_KEYS
    if unknown:
        errors.append(f"screenplay root uses unregistered fields: {sorted(unknown)}")

    runtime = data.get("runtime_context")
    required(runtime, ["validation_mode"], "runtime_context", errors)
    if isinstance(runtime, dict) and runtime.get("validation_mode") not in {"TEST_FIXTURE", "FORMAL_DELIVERY"}:
        errors.append("runtime_context.validation_mode must be TEST_FIXTURE or FORMAL_DELIVERY")

    source = data.get("source_contract")
    required(source, ["narrative_schema", "narrative_ir_id", "narrative_ir_version", "frozen_story_core_id"], "source_contract", errors)
    if isinstance(source, dict) and source.get("narrative_schema") != "PRISM-NARRATIVE-IR-1.1":
        errors.append("source_contract.narrative_schema must be PRISM-NARRATIVE-IR-1.1")

    policy = data.get("craft_policy")
    required(
        policy,
        ["visible_or_audible_only", "paragraph_unit", "camera_instruction_policy", "dominant_function_per_beat", "max_secondary_functions_per_beat"],
        "craft_policy",
        errors,
    )
    if isinstance(policy, dict):
        if policy.get("visible_or_audible_only") is not True:
            errors.append("craft_policy.visible_or_audible_only must be true")
        if policy.get("paragraph_unit") != "DRAMATIC_BEAT":
            errors.append("craft_policy.paragraph_unit must be DRAMATIC_BEAT")
        if policy.get("camera_instruction_policy") != "STORY_CRITICAL_ONLY":
            errors.append("craft_policy.camera_instruction_policy must be STORY_CRITICAL_ONLY")
        if policy.get("dominant_function_per_beat") != 1:
            errors.append("craft_policy.dominant_function_per_beat must equal 1")
        if policy.get("max_secondary_functions_per_beat") != 1:
            errors.append("craft_policy.max_secondary_functions_per_beat must equal 1")

    voiceprints = data.get("voiceprints")
    if not isinstance(voiceprints, list) or not voiceprints:
        errors.append("voiceprints must be a non-empty list")
        voiceprints = []
    voice_ids: set[str] = set()
    for index, voice in enumerate(voiceprints):
        label = f"voiceprints[{index}]"
        required(voice, ["voiceprint_id", "character_id", "default_speech_strategy", "sentence_shape", "lexical_domain", "rhythm_and_pause", "pressure_mutation"], label, errors)
        if not isinstance(voice, dict):
            continue
        vid = str(voice.get("voiceprint_id", ""))
        if vid in voice_ids:
            errors.append(f"{label}: duplicate voiceprint_id")
        voice_ids.add(vid)

    assets = data.get("structural_assets")
    if not isinstance(assets, list):
        errors.append("structural_assets must be a list")
        assets = []
    asset_ids: set[str] = set()
    for index, asset in enumerate(assets):
        label = f"structural_assets[{index}]"
        required(asset, ["asset_id", "topology_name", "quantity", "location", "connection_state", "damage_state"], label, errors)
        if not isinstance(asset, dict):
            continue
        aid = str(asset.get("asset_id", ""))
        if aid in asset_ids:
            errors.append(f"{label}: duplicate asset_id")
        asset_ids.add(aid)
        if not isinstance(asset.get("quantity"), int) or isinstance(asset.get("quantity"), bool) or asset.get("quantity", 0) < 1:
            errors.append(f"{label}: quantity must be a positive integer")

    scenes = data.get("scenes")
    if not isinstance(scenes, list) or not scenes:
        errors.append("scenes must be a non-empty list")
        scenes = []

    scene_ids: set[str] = set()
    beat_ids: set[str] = set()
    allocated_sum = 0.0
    for scene_index, scene in enumerate(scenes):
        label = f"scenes[{scene_index}]"
        required(
            scene,
            [
                "scene_id", "order", "t_in", "t_out", "scene_owner", "dramatic_question",
                "dominant_function", "attention_target", "entry_value", "exit_value", "scene_button",
                "handoff_from_previous", "state_in", "state_out", "pressure_ladder", "beats",
                "dialogue_units", "runtime_budget",
            ],
            label,
            errors,
        )
        if not isinstance(scene, dict):
            continue
        sid = str(scene.get("scene_id", ""))
        if sid in scene_ids:
            errors.append(f"{label}: duplicate scene_id")
        scene_ids.add(sid)
        if scene.get("order") != scene_index + 1:
            errors.append(f"{label}: order must equal {scene_index + 1}")
        t_in, t_out = scene.get("t_in"), scene.get("t_out")
        if not numeric(t_in) or not numeric(t_out) or float(t_out) <= float(t_in):
            errors.append(f"{label}: invalid t_in/t_out")
        entry, exit_value = scene.get("entry_value"), scene.get("exit_value")
        required(entry, ["axis", "state"], f"{label}.entry_value", errors)
        required(exit_value, ["axis", "state"], f"{label}.exit_value", errors)
        if isinstance(entry, dict) and isinstance(exit_value, dict):
            if entry.get("axis") != exit_value.get("axis"):
                errors.append(f"{label}: entry and exit value must use the same axis")
            if entry.get("state") == exit_value.get("state"):
                errors.append(f"{label}: scene must produce a value-state change")
        handoff = scene.get("handoff_from_previous")
        if handoff not in HANDOFFS:
            errors.append(f"{label}: unsupported handoff_from_previous")
        elif scene_index == 0 and handoff != "NONE_FIRST":
            errors.append(f"{label}: first scene must use NONE_FIRST handoff")
        elif scene_index > 0 and handoff == "NONE_FIRST":
            errors.append(f"{label}: non-first scene requires a legal handoff")

        pressure = scene.get("pressure_ladder")
        required(pressure, ["pressure_question", "mode", "steps", "peak_choice", "release_or_residue"], f"{label}.pressure_ladder", errors)
        if isinstance(pressure, dict):
            if pressure.get("mode") not in PRESSURE_MODES:
                errors.append(f"{label}.pressure_ladder: unsupported mode")
            steps = pressure.get("steps")
            if not isinstance(steps, list) or not steps:
                errors.append(f"{label}.pressure_ladder.steps must be a non-empty list")
            else:
                for step_index, step in enumerate(steps):
                    required(step, ["step_id", "trigger", "option_lost_or_cost_raised", "visible_or_audible_evidence", "character_response"], f"{label}.pressure_ladder.steps[{step_index}]", errors)

        beats = scene.get("beats")
        if not isinstance(beats, list) or not beats:
            errors.append(f"{label}.beats must be a non-empty list")
            beats = []
        local_beat_ids: set[str] = set()
        for beat_index, beat in enumerate(beats):
            beat_label = f"{label}.beats[{beat_index}]"
            required(
                beat,
                [
                    "beat_id", "primary_function", "secondary_functions", "trigger", "active_character",
                    "local_objective", "tactic", "expected_result", "counterforce", "expectation_gap",
                    "tactic_shift_or_turn", "turn_type", "observable_action_or_sound", "observability",
                    "information_delta", "value_delta", "state_delta", "next_necessity",
                ],
                beat_label,
                errors,
            )
            if not isinstance(beat, dict):
                continue
            bid = str(beat.get("beat_id", ""))
            if bid in beat_ids:
                errors.append(f"{beat_label}: duplicate beat_id")
            beat_ids.add(bid)
            local_beat_ids.add(bid)
            primary = beat.get("primary_function")
            if not isinstance(primary, str) or primary not in PRIMARY_FUNCTIONS:
                errors.append(f"{beat_label}: primary_function must be one supported scalar function")
            secondary = beat.get("secondary_functions")
            if not isinstance(secondary, list):
                errors.append(f"{beat_label}: secondary_functions must be a list")
            elif len(secondary) > 1:
                errors.append(f"{beat_label}: secondary functions exceed the per-beat attention budget")
            if beat.get("turn_type") not in TURN_TYPES:
                errors.append(f"{beat_label}: unsupported turn_type")
            if beat.get("observability") not in OBSERVABILITY:
                errors.append(f"{beat_label}: observability must be VISIBLE, AUDIBLE or PERFORMANCE_INFERENCE")
            delta = beat.get("state_delta")
            required(delta, ["before", "after", "cause", "evidence"], f"{beat_label}.state_delta", errors)
            if isinstance(delta, dict) and delta.get("before") == delta.get("after"):
                errors.append(f"{beat_label}: state_delta before and after must differ")
            instruction = beat.get("director_instruction")
            if instruction not in (None, "", {}, []):
                reason = beat.get("story_critical_reason")
                if not reason:
                    errors.append(f"{beat_label}: director instruction leaks into screenplay without story-critical reason")

        dialogues = scene.get("dialogue_units")
        if not isinstance(dialogues, list):
            errors.append(f"{label}.dialogue_units must be a list")
            dialogues = []
        dialogue_ids: set[str] = set()
        for dialogue_index, dialogue in enumerate(dialogues):
            dialogue_label = f"{label}.dialogue_units[{dialogue_index}]"
            required(
                dialogue,
                [
                    "dialogue_id", "beat_id", "speaker", "listener", "knowledge_basis", "listener_need",
                    "why_now", "disclosure_risk", "speech_action", "truth_mode", "line", "referent_status",
                    "referent_anchors", "image_relation", "response_type", "listener_response",
                    "exchange_result", "voiceprint_id", "playability",
                ],
                dialogue_label,
                errors,
            )
            if not isinstance(dialogue, dict):
                continue
            did = str(dialogue.get("dialogue_id", ""))
            if did in dialogue_ids:
                errors.append(f"{dialogue_label}: duplicate dialogue_id")
            dialogue_ids.add(did)
            if dialogue.get("beat_id") not in local_beat_ids:
                errors.append(f"{dialogue_label}: beat_id must resolve within its scene")
            if dialogue.get("voiceprint_id") not in voice_ids:
                errors.append(f"{dialogue_label}: voiceprint_id must resolve")
            if dialogue.get("truth_mode") not in TRUTH_MODES:
                errors.append(f"{dialogue_label}: unsupported truth_mode")
            if dialogue.get("image_relation") not in IMAGE_RELATIONS:
                errors.append(f"{dialogue_label}: unsupported image_relation")
            if dialogue.get("response_type") not in RESPONSE_TYPES:
                errors.append(f"{dialogue_label}: unsupported response_type")
            referent = dialogue.get("referent_status")
            if referent not in REFERENT_STATUSES:
                errors.append(f"{dialogue_label}: unsupported referent_status")
            anchors = dialogue.get("referent_anchors")
            if referent == "CLEAR" and (not isinstance(anchors, list) or not anchors):
                errors.append(f"{dialogue_label}: CLEAR referent requires at least one audience-reachable anchor")
            if referent == "INTENTIONAL_AMBIGUITY":
                if not dialogue.get("ambiguity_purpose") or not dialogue.get("ambiguity_payoff"):
                    errors.append(f"{dialogue_label}: intentional ambiguity requires purpose and payoff")
            if dialogue.get("image_relation") == "DUPLICATE" and not dialogue.get("duplicate_exception_reason"):
                errors.append(f"{dialogue_label}: DUPLICATE image relation requires a dramatic exception reason")
            if dialogue.get("response_type") == "IGNORE_WITH_EVIDENCE" and not dialogue.get("listener_evidence"):
                errors.append(f"{dialogue_label}: evidenced ignore requires listener_evidence")
            playability = dialogue.get("playability")
            required(playability, ["physical_load", "breath_window", "competing_sound", "listener_can_hear", "line_split_required"], f"{dialogue_label}.playability", errors)
            if isinstance(playability, dict) and playability.get("listener_can_hear") is not True:
                errors.append(f"{dialogue_label}: critical dialogue must be audible to its listener")

        scene_budget = scene.get("runtime_budget")
        validate_runtime_budget(scene_budget, f"{label}.runtime_budget", errors)
        if isinstance(scene_budget, dict) and numeric(scene_budget.get("allocated_seconds")):
            allocated_sum += float(scene_budget["allocated_seconds"])
            if numeric(t_in) and numeric(t_out) and abs(float(scene_budget["allocated_seconds"]) - (float(t_out) - float(t_in))) > 0.2:
                errors.append(f"{label}: runtime allocation must match t_in/t_out")

    budget = data.get("runtime_budget")
    required(budget, ["total_duration_seconds", "scene_budget_total_seconds", "test_status"], "runtime_budget", errors)
    if isinstance(budget, dict):
        total = budget.get("total_duration_seconds")
        scene_total = budget.get("scene_budget_total_seconds")
        if not numeric(total) or float(total) <= 0:
            errors.append("runtime_budget.total_duration_seconds must be positive")
        if not numeric(scene_total) or float(scene_total) <= 0:
            errors.append("runtime_budget.scene_budget_total_seconds must be positive")
        elif numeric(total) and abs(float(total) - float(scene_total)) > 0.2:
            errors.append("runtime_budget scene total must equal project duration")
        if numeric(scene_total) and abs(float(scene_total) - allocated_sum) > 0.2:
            errors.append("runtime_budget scene total must equal the sum of scene allocations")

    receipt = data.get("layer_receipt")
    required(receipt, ["layer_type", "status", "source_layer_id", "source_version", "output_version", "preserved_truth_ids", "transformed_field_ids"], "layer_receipt", errors)
    if isinstance(receipt, dict):
        if receipt.get("layer_type") != "SCREENPLAY":
            errors.append("layer_receipt.layer_type must be SCREENPLAY")
        if receipt.get("status") != "VALIDATED":
            errors.append("layer_receipt.status must be VALIDATED")
        if not isinstance(receipt.get("preserved_truth_ids"), list) or not receipt.get("preserved_truth_ids"):
            errors.append("layer_receipt.preserved_truth_ids must be non-empty")
        if not isinstance(receipt.get("transformed_field_ids"), list) or not receipt.get("transformed_field_ids"):
            errors.append("layer_receipt.transformed_field_ids must be non-empty")

    return errors, warnings


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path", type=Path)
    args = parser.parse_args()
    try:
        data = load_document(args.path)
        errors, warnings = validate(data)
    except Exception as exc:  # pragma: no cover
        print(json.dumps({"status": "FAIL", "errors": [str(exc)], "warnings": []}, ensure_ascii=False, indent=2))
        return 1
    status = "PASS" if not errors else "FAIL"
    print(json.dumps({"status": status, "errors": errors, "warnings": warnings}, ensure_ascii=False, indent=2))
    return 0 if status == "PASS" else 1


if __name__ == "__main__":
    sys.exit(main())
