#!/usr/bin/env python3
"""Validate PRISM-NARRATIVE-IR-1.1 story, scene-life, audience and ending 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-NARRATIVE-IR-1.1"
ALLOWED_CONTROLLERS = {"WANFU", "PRISM_STANDALONE"}
ALLOWED_RESULTS = {"YES", "NO", "YES_BUT", "NO_AND", "PARTIAL", "MISLEADING_SUCCESS", "REDEFINED_GOAL"}
ALLOWED_CONNECTORS = {"THEREFORE", "BUT", "CONSEQUENCE", "REVEAL", "PAYOFF", "SIMULTANEOUS_PRESSURE"}
CREATIVE_OWNED_FIELDS = {
    "concept_truth",
    "story_truth",
    "plot",
    "character_truth",
    "world_truth",
    "structure",
    "information_truth",
    "climax",
    "scene_outcome",
    "beat_truth",
    "relationship_truth",
    "promise_payoff",
    "environment_truth",
    "audience_experience",
    "offscreen_world_truth",
    "ending_truth",
}
ALLOWED_FIELD_OWNERS = {field: "CREATIVE_TO_NARRATIVE" for field in CREATIVE_OWNED_FIELDS}
LAYER_ORDER = {
    "NARRATIVE_IR": 0,
    "STORY_BLUEPRINT": 1,
    "SCREENPLAY": 2,
    "DIRECTOR_SHOOTING_SCRIPT": 3,
    "ATOMIC_VIDEO_PACKAGE": 4,
}
LAYER_STATUSES = {"CREATED", "VALIDATED", "REJECTED", "PENDING_CREATIVE_REVIEW"}
SHANYIN_GAP_MANIFEST_ID = "SHANYIN-GAP-MANIFEST-001"
SHANYIN_GAP_RECEIPT_ID = "SHANYIN-GAP-RECEIPT-001"
SHANYIN_SOURCE_MANIFEST_ID = "SHANYIN-SOURCE-MANIFEST-001"
SHANYIN_SOURCE_RECEIPT_ID = "SHANYIN-SOURCE-RECEIPT-001"
SHANYIN_VERIFIED_HASH = "5be8e1b9fab372c4d418a4e79c19d20eafc5af217020a1a7a1857d89d5a774ba"
SHANYIN_FALLBACK = "CREATIVE_LONGFORM_AND_CONTINUITY_AUDIT"
SHANYIN_STATUSES = {"SOURCE_VERIFIED", "SOURCE_BODY_MISSING"}
CONCEPT_MODES = {"DRAMATIC_CORE", "WHAT_IF_RULE", "HOW_TO_TELL_FORM", "HYBRID"}
SCENE_ENTRY_MODES = {
    "WORLD_FIRST", "AFTERMATH_FIRST", "SOUND_FIRST", "OBJECT_FIRST", "ABSENCE_FIRST",
    "IN_MEDIAS_RES", "MISREAD_FIRST", "DAILY_CRACK", "CHARACTER_FIRST",
}
ENVIRONMENT_FUNCTIONS = {
    "ORIENT", "PRESSURE", "EVIDENCE", "OPPOSITION", "AFFORDANCE",
    "COUNTERPOINT", "FEEDBACK", "RESIDUE", "TRANSITION",
}
ENVIRONMENT_RESPONSE_STATUSES = {"ACTIVE", "NONE_BY_DESIGN"}
ENVIRONMENT_TRIGGER_TYPES = {"CHARACTER_ACTION", "PHYSICAL_PROCESS", "SOCIAL_ACTION", "WORLD_RULE", "NONE"}
OFFSCREEN_STATUSES = {"ACTIVE", "NONE_BY_DESIGN"}
ENDING_EMOTIONAL_RESULTS = {"HE", "BE", "BITTERSWEET", "NEUTRAL"}
ENDING_CAUSAL_CLOSURES = {"CLOSED", "OPEN"}
ENDING_REVELATION_MODES = {"STANDARD", "TRUE_ENDING", "FALSE_ENDING", "RECONTEXTUALIZED"}
ENDING_STRUCTURAL_SHAPES = {"LINEAR", "CYCLIC", "TRANSCENDENT", "BRANCHING"}
ENDING_SETTLEMENT_KEYS = {"external_goal", "inner_need", "core_relationship", "identity_or_value", "truth", "world"}
ENDING_SETTLEMENT_STATUSES = {"GAIN", "LOSS", "MIXED", "UNCHANGED", "OPEN"}
SPAN_DURATION_SECONDS = {"30_MIN_EPISODE": 1800}
NARRATIVE_ROOT_KEYS = {
    "schema_version",
    "runtime_context",
    "authority_contract",
    "source_registry",
    "source_contract",
    "shanyin_runtime_receipt",
    "task_contract",
    "concept_contract",
    "frozen_story_core",
    "world",
    "characters",
    "relationships",
    "dramaturgy",
    "scene_life_contract",
    "structure",
    "episode_contract",
    "information",
    "experience",
    "expression",
    "continuity",
    "spatial",
    "climax_gate",
    "ending_contract",
    "layer_receipts",
    "decision_registry",
    "output_state",
}


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 contains_missing_shanyin(source: dict[str, Any]) -> bool:
    return any(
        ("SHANYIN" in json.dumps(item, ensure_ascii=False).upper() or "山音" in json.dumps(item, ensure_ascii=False))
        and ("MISSING" in json.dumps(item, ensure_ascii=False).upper() or "缺失" in json.dumps(item, ensure_ascii=False))
        for item in source.get("source_gaps", []) or []
    )


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_root_keys = set(data) - NARRATIVE_ROOT_KEYS
    if unknown_root_keys:
        errors.append(f"narrative root uses unregistered fields: {sorted(unknown_root_keys)}")

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

    authority = data.get("authority_contract")
    required(authority, ["controller", "controller_count", "field_owners"], "authority_contract", errors)
    if isinstance(authority, dict):
        if authority.get("controller") not in ALLOWED_CONTROLLERS:
            errors.append("authority_contract.controller must be WANFU or PRISM_STANDALONE")
        if authority.get("controller_count") != 1:
            errors.append("authority_contract.controller_count must equal 1")
        if isinstance(runtime, dict) and runtime.get("embedded_in_wanfu") is True:
            if authority.get("controller") != "WANFU" or runtime.get("parent_controller") != "WANFU":
                errors.append("embedded narrative runtime must use WANFU as parent and sole controller")
        owners = authority.get("field_owners", {})
        if not isinstance(owners, dict):
            errors.append("authority_contract.field_owners must be an object")
            owners = {}
        for field, owner in owners.items():
            if field not in ALLOWED_FIELD_OWNERS:
                errors.append(f"unknown narrative field owner key: {field}")
            elif owner != ALLOWED_FIELD_OWNERS[field]:
                errors.append(f"field owner mismatch: {field} must be CREATIVE_TO_NARRATIVE")
        for field in CREATIVE_OWNED_FIELDS:
            if owners.get(field) != "CREATIVE_TO_NARRATIVE":
                errors.append(f"Creative-owned field missing or reassigned: {field}")
        if any(str(owner).upper().startswith("SHANYIN") for field, owner in owners.items() if field in CREATIVE_OWNED_FIELDS):
            errors.append("ShanYin cannot own story-truth fields")

    registry = data.get("source_registry")
    if not isinstance(registry, dict):
        errors.append("source_registry must be an object")
        registry = {}
    shanyin_source = registry.get("SHANYIN")
    required(shanyin_source, ["status", "source_version", "authorship_status", "manifest_id", "validation_receipt_id"], "source_registry.SHANYIN", errors)
    shanyin_status = shanyin_source.get("status") if isinstance(shanyin_source, dict) else None
    if shanyin_status not in SHANYIN_STATUSES:
        errors.append("SHANYIN status must be SOURCE_VERIFIED or SOURCE_BODY_MISSING")
    elif shanyin_status == "SOURCE_VERIFIED":
        if shanyin_source.get("source_hash") != SHANYIN_VERIFIED_HASH:
            errors.append("verified ShanYin source hash does not match the release evidence")
        if shanyin_source.get("source_version") != "VERSION_UNDECLARED":
            errors.append("verified ShanYin source must preserve VERSION_UNDECLARED")
        if shanyin_source.get("authorship_status") != "AUTHORSHIP_UNVERIFIED":
            errors.append("verified ShanYin source must preserve AUTHORSHIP_UNVERIFIED")
        if shanyin_source.get("manifest_id") != SHANYIN_SOURCE_MANIFEST_ID or shanyin_source.get("validation_receipt_id") != SHANYIN_SOURCE_RECEIPT_ID:
            errors.append("verified ShanYin source must bind the immutable source manifest IDs")
    elif shanyin_source.get("source_hash") is not None:
        errors.append("missing ShanYin body must use source_hash null")
    elif shanyin_source.get("manifest_id") != SHANYIN_GAP_MANIFEST_ID or shanyin_source.get("validation_receipt_id") != SHANYIN_GAP_RECEIPT_ID:
        errors.append("missing ShanYin source must bind the immutable gap manifest IDs")

    source = data.get("source_contract")
    required(source, ["narrative_ir_id", "narrative_ir_version", "primary_source", "active_sources"], "source_contract", errors)
    if not isinstance(source, dict):
        source = {}
    if "source_gaps" not in source or not isinstance(source.get("source_gaps"), list):
        errors.append("source_contract.source_gaps must be a list")
    if source.get("primary_source") != "CREATIVE_TO_NARRATIVE":
        errors.append("source_contract.primary_source must be CREATIVE_TO_NARRATIVE")
    active_shanyin = any("SHANYIN" in str(item).upper() or "山音" in str(item) for item in source.get("active_sources", []) or [])
    missing_gap = contains_missing_shanyin(source)
    receipt = data.get("shanyin_runtime_receipt")
    required(receipt, ["requested", "invoked", "status", "decision", "adapter_profile", "fallback", "source_version", "authorship_status", "source_manifest_id", "validation_receipt_id"], "shanyin_runtime_receipt", errors)
    if shanyin_status == "SOURCE_VERIFIED":
        if not active_shanyin:
            errors.append("verified ShanYin adapter must appear in active_sources when requested")
        if missing_gap:
            errors.append("verified ShanYin source cannot also be declared missing")
        if isinstance(receipt, dict):
            if receipt.get("status") != "SOURCE_VERIFIED" or receipt.get("invoked") is not True:
                errors.append("verified ShanYin request requires invocation as a secondary adapter")
            if receipt.get("decision") != "INVOKE_AS_SECONDARY_ADAPTER" or receipt.get("adapter_profile") != "SHANYIN_DELTA_ONLY" or receipt.get("fallback") != "NONE":
                errors.append("verified ShanYin receipt must use the delta-only adapter profile")
            if receipt.get("source_version") != "VERSION_UNDECLARED" or receipt.get("authorship_status") != "AUTHORSHIP_UNVERIFIED":
                errors.append("ShanYin receipt must preserve source version and authorship uncertainty")
            if receipt.get("source_manifest_id") != SHANYIN_SOURCE_MANIFEST_ID or receipt.get("validation_receipt_id") != SHANYIN_SOURCE_RECEIPT_ID:
                errors.append("ShanYin runtime receipt must bind the verified source registry")
    else:
        if active_shanyin:
            errors.append("missing ShanYin source cannot appear in active_sources")
        if not missing_gap:
            errors.append("missing ShanYin source must expose the authoritative source gap")
        if isinstance(receipt, dict):
            if receipt.get("invoked") is not False or receipt.get("status") != "SOURCE_BODY_MISSING":
                errors.append("ShanYin cannot be invoked while SOURCE_BODY_MISSING")
            if receipt.get("fallback") != SHANYIN_FALLBACK:
                errors.append("missing ShanYin narrative receipt requires the Creative fallback")
            if receipt.get("source_manifest_id") != SHANYIN_GAP_MANIFEST_ID or receipt.get("validation_receipt_id") != SHANYIN_GAP_RECEIPT_ID:
                errors.append("ShanYin runtime receipt must bind the missing-source registry")
    forbidden = {"shanyin_eight_steps", "shanyin_five_steps", "screenwriting_eight_steps", "director_five_steps"}
    if forbidden & set(data):
        errors.append("invented or promoted ShanYin fixed-step body detected")

    task = data.get("task_contract")
    required(task, ["project_id", "output_target", "medium", "span", "requested_duration_seconds", "project_goal_layers", "current_delivery_layers", "delivery_scope", "primary_genre", "experience_target", "frozen_assets", "hard_constraints"], "task_contract", errors)
    if isinstance(task, dict):
        if task.get("delivery_scope") not in {"INTERMEDIATE", "FINAL"}:
            errors.append("task_contract.delivery_scope must be INTERMEDIATE or FINAL")
        for key in ("project_goal_layers", "current_delivery_layers"):
            values = task.get(key)
            if not isinstance(values, list) or not values or any(value not in LAYER_ORDER or value == "NARRATIVE_IR" for value in values):
                errors.append(f"task_contract.{key} must contain registered output layers")

    concept = data.get("concept_contract")
    required(
        concept,
        ["concept_id", "status", "mode", "human_or_world_anchor", "governing_rule_or_form", "visible_or_audible_proof", "protagonist_pressure", "consequence_ladder", "form_contract", "clean_motif", "ending_test", "creative_decision_id", "source_candidate_ids"],
        "concept_contract",
        errors,
    )
    if isinstance(concept, dict):
        mode = concept.get("mode")
        if concept.get("status") != "CREATIVE_APPROVED":
            errors.append("concept_contract.status must be CREATIVE_APPROVED")
        if mode not in CONCEPT_MODES:
            errors.append("concept_contract.mode is unsupported")
        ladder = concept.get("consequence_ladder")
        if mode in {"WHAT_IF_RULE", "HYBRID"}:
            if not isinstance(ladder, list) or len(ladder) < 3:
                errors.append("WHAT_IF/HYBRID concept requires at least three consequence-ladder nodes")
            else:
                domains = {str(item.get("domain")) for item in ladder if isinstance(item, dict) and item.get("domain")}
                if len(domains) < 2:
                    errors.append("concept consequence ladder must change at least two distinct domains")
        form = concept.get("form_contract")
        if mode in {"HOW_TO_TELL_FORM", "HYBRID"}:
            required(form, ["form", "necessity", "escalation", "convergence", "break_condition"], "concept_contract.form_contract", errors)
        motif = concept.get("clean_motif")
        required(motif, ["motif_id", "semantic_job", "first_proof", "recurrence_rule", "mutation_rule", "convergence_or_break"], "concept_contract.clean_motif", errors)

    core = data.get("frozen_story_core")
    required(
        core,
        ["core_id", "concept_id", "one_sentence_premise", "protagonist", "active_desire", "central_opposition", "stakes", "open_question", "unique_mechanism", "story_promises", "ending_test"],
        "frozen_story_core",
        errors,
    )
    if isinstance(core, dict):
        if isinstance(concept, dict) and core.get("concept_id") != concept.get("concept_id"):
            errors.append("frozen_story_core.concept_id must reference concept_contract")
        promises = core.get("story_promises")
        if not isinstance(promises, dict) or not promises:
            errors.append("frozen_story_core.story_promises must be an ID-keyed object")
        else:
            promise_types = {item.get("type") for item in promises.values() if isinstance(item, dict)}
            if not {"dramatic", "emotional", "genre", "transformation"}.issubset(promise_types):
                errors.append("story promises must include dramatic/emotional/genre/transformation types")

    world = data.get("world")
    required(world, ["hypothesis", "rules", "current_state"], "world", errors)

    characters = data.get("characters")
    if not isinstance(characters, list) or len(characters) < 2:
        errors.append("characters must contain at least protagonist and opposition")
        character_ids: set[str] = set()
    else:
        character_ids = set()
        for idx, character in enumerate(characters):
            cid = str(character.get("character_id") or f"characters[{idx}]") if isinstance(character, dict) else f"characters[{idx}]"
            required(character, ["character_id", "role", "active_want", "belief", "contradiction", "decision_signature"], cid, errors)
            if cid in character_ids:
                errors.append(f"duplicate character_id: {cid}")
            character_ids.add(cid)
    if isinstance(core, dict) and core.get("protagonist") not in character_ids:
        errors.append("frozen_story_core.protagonist must reference a character_id")

    relationships = data.get("relationships")
    required(relationships, ["graph", "current_states"], "relationships", errors)

    experience = data.get("experience")
    required(
        experience,
        ["body", "emotion", "interpretation", "misreading", "memory", "belief_updates"],
        "experience",
        errors,
    )

    expression = data.get("expression")
    required(expression, ["pov", "distance", "dialogue_rules", "motifs", "tone", "style_contract"], "expression", errors)

    continuity = data.get("continuity")
    required(continuity, ["timeline", "locations", "entities", "props", "unresolved_motion"], "continuity", errors)

    spatial = data.get("spatial")
    required(spatial, ["world_frame", "zones", "routes", "camera_frames"], "spatial", errors)

    dramaturgy = data.get("dramaturgy")
    required(dramaturgy, ["desire", "opposition", "stakes", "escalation", "dilemma", "climax_choice"], "dramaturgy", errors)

    structure = data.get("structure")
    required(structure, ["profile", "total_duration", "scenes"], "structure", errors)
    if not isinstance(structure, dict):
        return errors, warnings
    total_duration = structure.get("total_duration")
    if not numeric(total_duration) or total_duration <= 0:
        errors.append("structure.total_duration must be a positive finite number")
    if isinstance(task, dict):
        requested_duration = task.get("requested_duration_seconds")
        if not numeric(requested_duration) or requested_duration <= 0:
            errors.append("task_contract.requested_duration_seconds must be a positive number")
        elif numeric(total_duration) and requested_duration != total_duration:
            errors.append("task requested duration must match structure.total_duration")
        span = str(task.get("span", ""))
        if span in SPAN_DURATION_SECONDS and requested_duration != SPAN_DURATION_SECONDS[span]:
            errors.append(f"task span {span} requires {SPAN_DURATION_SECONDS[span]} seconds")

    scenes = structure.get("scenes")
    if not isinstance(scenes, list) or not scenes:
        errors.append("structure.scenes must be a non-empty list")
        return errors, warnings

    scene_ids: list[str] = []
    source_scene_ids: set[str] = set()
    source_beat_ids: set[str] = set()
    scene_by_id: dict[str, dict[str, Any]] = {}
    windows: list[tuple[float, float, str]] = []
    for idx, scene in enumerate(scenes):
        sid = str(scene.get("scene_id") or f"scene[{idx}]") if isinstance(scene, dict) else f"scene[{idx}]"
        required(
            scene,
            ["scene_id", "source_scene_id", "order", "t_in", "t_out", "function", "pov", "entry_state", "active_desire", "opposition_action", "protagonist_choice", "turning_point", "outcome", "cost", "state_delta", "exit_state", "next_pressure", "visible_or_audible_evidence", "resulting_state_id"],
            sid,
            errors,
        )
        if not isinstance(scene, dict):
            continue
        for list_key in ("established_resource_ids", "paid_promise_ids"):
            if list_key not in scene or not isinstance(scene.get(list_key), list):
                errors.append(f"{sid}: {list_key} must be a list")
        if sid in scene_by_id:
            errors.append(f"duplicate scene_id: {sid}")
        source_scene_id = str(scene.get("source_scene_id", ""))
        if source_scene_id in source_scene_ids:
            errors.append(f"duplicate source_scene_id: {source_scene_id}")
        source_scene_ids.add(source_scene_id)
        for beat in scene.get("beats", []) or []:
            if not isinstance(beat, dict) or not beat.get("beat_id"):
                errors.append(f"{sid}: every beat requires beat_id")
                continue
            beat_id = str(beat.get("beat_id"))
            if beat_id in source_beat_ids:
                errors.append(f"duplicate source beat_id: {beat_id}")
            source_beat_ids.add(beat_id)
        scene_ids.append(sid)
        scene_by_id[sid] = scene
        if scene.get("order") != idx + 1:
            errors.append(f"{sid}: order must equal {idx + 1}")
        st, et = scene.get("t_in"), scene.get("t_out")
        if not numeric(st) or not numeric(et) or et <= st:
            errors.append(f"{sid}: invalid t_in/t_out")
        else:
            windows.append((float(st), float(et), sid))
        if scene.get("outcome") not in ALLOWED_RESULTS:
            errors.append(f"{sid}: unsupported outcome {scene.get('outcome')}")
        delta = scene.get("state_delta")
        if not isinstance(delta, dict) or not any(value not in (None, "", [], {}) for value in delta.values()):
            errors.append(f"{sid}: state_delta must contain a material change")
        choice = str(scene.get("protagonist_choice", "")).strip().lower()
        if choice in {"", "none", "n/a", "无", "没有"}:
            errors.append(f"{sid}: protagonist must make or refuse a consequential choice")
        if idx == 0:
            if scene.get("caused_by_scene_id") not in (None, ""):
                warnings.append(f"{sid}: first scene normally has no caused_by_scene_id")
        else:
            cause = scene.get("caused_by_scene_id")
            connector = scene.get("causal_connector")
            if cause not in scene_ids[:-1]:
                errors.append(f"{sid}: caused_by_scene_id must reference an earlier scene")
            if connector not in ALLOWED_CONNECTORS:
                errors.append(f"{sid}: causal_connector must be one of {sorted(ALLOWED_CONNECTORS)}")

    windows.sort()
    if windows and abs(windows[0][0]) > 1e-6:
        errors.append("first scene must start at 0")
    for prev, cur in zip(windows, windows[1:]):
        if cur[0] < prev[1] - 1e-6:
            errors.append(f"scene overlap: {prev[2]} and {cur[2]}")
        elif cur[0] > prev[1] + 1e-6:
            errors.append(f"scene gap: {prev[2]} to {cur[2]}")
    if numeric(total_duration) and windows and abs(float(total_duration) - windows[-1][1]) > 1e-6:
        errors.append("last scene end must equal structure.total_duration")

    scene_life = data.get("scene_life_contract")
    required(scene_life, ["policy", "ledger"], "scene_life_contract", errors)
    if isinstance(scene_life, dict):
        policy = scene_life.get("policy")
        required(
            policy,
            [
                "world_preexists_characters",
                "atmosphere_is_functional",
                "environment_requires_cause",
                "audience_state_is_separate",
                "offscreen_world_continues",
                "density_rule",
            ],
            "scene_life_contract.policy",
            errors,
        )
        if isinstance(policy, dict):
            for key in (
                "world_preexists_characters",
                "atmosphere_is_functional",
                "environment_requires_cause",
                "audience_state_is_separate",
                "offscreen_world_continues",
            ):
                if policy.get(key) is not True:
                    errors.append(f"scene_life_contract.policy.{key} must be true")
            if policy.get("density_rule") != "MINIMUM_SUFFICIENT":
                errors.append("scene_life_contract.policy.density_rule must be MINIMUM_SUFFICIENT")

        life_ledger = scene_life.get("ledger")
        if not isinstance(life_ledger, list) or not life_ledger:
            errors.append("scene_life_contract.ledger must be a non-empty list")
        else:
            seen_life_ids: set[str] = set()
            covered_scene_ids: set[str] = set()
            for idx, item in enumerate(life_ledger):
                label = f"scene_life_contract.ledger[{idx}]"
                required(
                    item,
                    [
                        "scene_life_id",
                        "scene_id",
                        "entry_mode",
                        "baseline",
                        "prehistory_trace",
                        "pressure_or_anomaly",
                        "sensory_evidence",
                        "environmental_function",
                        "environment_response",
                        "residue",
                        "next_handoff",
                        "audience_state",
                        "offscreen_world",
                    ],
                    label,
                    errors,
                )
                if not isinstance(item, dict):
                    continue
                life_id = str(item.get("scene_life_id", ""))
                sid = str(item.get("scene_id", ""))
                if life_id in seen_life_ids:
                    errors.append(f"{label}: duplicate scene_life_id")
                seen_life_ids.add(life_id)
                if sid in covered_scene_ids:
                    errors.append(f"{label}: duplicate scene_id coverage")
                covered_scene_ids.add(sid)
                if sid not in scene_by_id:
                    errors.append(f"{label}: scene_id must reference structure.scenes")
                if item.get("entry_mode") not in SCENE_ENTRY_MODES:
                    errors.append(f"{label}: unsupported entry_mode")
                sensory = item.get("sensory_evidence")
                if not isinstance(sensory, list) or not sensory:
                    errors.append(f"{label}: sensory_evidence must contain at least one observable item")
                if item.get("environmental_function") not in ENVIRONMENT_FUNCTIONS:
                    errors.append(f"{label}: unsupported environmental_function")

                response = item.get("environment_response")
                required(response, ["status", "trigger_type", "narrative_job"], f"{label}.environment_response", errors)
                if isinstance(response, dict):
                    response_status = response.get("status")
                    trigger_type = response.get("trigger_type")
                    if response_status not in ENVIRONMENT_RESPONSE_STATUSES:
                        errors.append(f"{label}.environment_response: unsupported status")
                    if trigger_type not in ENVIRONMENT_TRIGGER_TYPES:
                        errors.append(f"{label}.environment_response: unsupported trigger_type")
                    if response_status == "ACTIVE":
                        required(
                            response,
                            ["trigger_ref", "affected_entity_or_zone", "visible_or_audible_result", "decay_or_settle"],
                            f"{label}.environment_response",
                            errors,
                        )
                        if trigger_type == "NONE":
                            errors.append(f"{label}.environment_response: ACTIVE response cannot use trigger_type NONE")
                    elif response_status == "NONE_BY_DESIGN" and trigger_type != "NONE":
                        errors.append(f"{label}.environment_response: NONE_BY_DESIGN must use trigger_type NONE")

                audience = item.get("audience_state")
                required(
                    audience,
                    ["knows", "assumes_or_questions", "intended_affect", "belief_update"],
                    f"{label}.audience_state",
                    errors,
                )
                offscreen = item.get("offscreen_world")
                required(offscreen, ["status"], f"{label}.offscreen_world", errors)
                if isinstance(offscreen, dict):
                    status = offscreen.get("status")
                    if status not in OFFSCREEN_STATUSES:
                        errors.append(f"{label}.offscreen_world: unsupported status")
                    elif status == "ACTIVE":
                        required(offscreen, ["active_force", "evidence", "consequence"], f"{label}.offscreen_world", errors)

            if covered_scene_ids != set(scene_by_id):
                missing = sorted(set(scene_by_id) - covered_scene_ids)
                extra = sorted(covered_scene_ids - set(scene_by_id))
                errors.append(f"scene_life_contract must cover every scene exactly once; missing={missing}, extra={extra}")

    profile = structure.get("profile")
    episode = data.get("episode_contract")
    if profile == "EPISODE":
        required(episode, ["requested_duration_seconds", "episode_question", "episode_satisfaction", "long_term_question", "a_story_scene_ids", "b_story_scene_ids", "act_or_sequence_turns", "midpoint_scene_id", "midpoint_redefinition", "climax_scene_id", "climax_choice", "end_hook_scene_id", "end_hook", "continuity_debt"], "episode_contract", errors)
        if isinstance(episode, dict) and isinstance(dramaturgy, dict) and episode.get("climax_choice") != dramaturgy.get("climax_choice"):
            errors.append("episode_contract.climax_choice must match dramaturgy.climax_choice")
        if isinstance(episode, dict):
            if episode.get("requested_duration_seconds") != total_duration:
                errors.append("episode requested duration must match structure.total_duration")
            if isinstance(task, dict) and episode.get("requested_duration_seconds") != task.get("requested_duration_seconds"):
                errors.append("episode requested duration must match task requested duration")
            a_ids = episode.get("a_story_scene_ids", []) or []
            b_ids = episode.get("b_story_scene_ids", []) or []
            for label, ids in (("a_story_scene_ids", a_ids), ("b_story_scene_ids", b_ids)):
                if not isinstance(ids, list) or not ids or any(item not in scene_by_id for item in ids):
                    errors.append(f"episode_contract.{label} must reference existing scenes")
                elif len(ids) != len(set(map(str, ids))):
                    errors.append(f"episode_contract.{label} contains duplicate scene IDs")
            turns = episode.get("act_or_sequence_turns", []) or []
            turn_ids: list[str] = []
            for idx, turn in enumerate(turns):
                required(turn, ["scene_id", "function"], f"episode_contract.act_or_sequence_turns[{idx}]", errors)
                if isinstance(turn, dict):
                    turn_ids.append(str(turn.get("scene_id")))
            if len(turn_ids) != len(set(turn_ids)):
                errors.append("episode act_or_sequence_turns contains duplicate scene IDs")
            if any(item not in scene_by_id for item in turn_ids) or turn_ids != sorted(turn_ids, key=lambda item: scene_ids.index(item) if item in scene_by_id else 10**9):
                errors.append("episode turn scene IDs must exist and be in story order")
            midpoint_id, climax_id, hook_id = episode.get("midpoint_scene_id"), episode.get("climax_scene_id"), episode.get("end_hook_scene_id")
            if any(item not in scene_by_id for item in (midpoint_id, climax_id, hook_id)):
                errors.append("episode midpoint/climax/end-hook IDs must reference existing scenes")
            elif not scene_ids.index(midpoint_id) < scene_ids.index(climax_id) < scene_ids.index(hook_id):
                errors.append("episode midpoint must precede climax, which must precede end hook")
            if climax_id in scene_by_id and climax_id not in a_ids:
                errors.append("episode A-story must cover the climax scene")
            if len(b_ids) < 2 or any(not scene_by_id[item].get("state_delta") for item in b_ids if item in scene_by_id):
                errors.append("episode B-story must span at least two state-changing scenes")

    information = data.get("information")
    required(information, ["mode", "questions", "promises", "ledger"], "information", errors)
    suspense = False
    if isinstance(task, dict):
        suspense = any(token in str(task.get("primary_genre", "")).upper() for token in ("MYSTERY", "SUSPENSE", "悬疑", "推理"))
    if isinstance(information, dict):
        suspense = suspense or information.get("mode") == "SUSPENSE"
        ledger = information.get("ledger")
        if suspense and (not isinstance(ledger, list) or len(ledger) < 2):
            errors.append("suspense work requires at least two information-ledger entries")
        truth_ids: set[str] = set()
        decisive_count = 0
        for idx, item in enumerate(ledger or []):
            label = f"information.ledger[{idx}]"
            required(item, ["truth_id", "objective_fact", "who_knows", "audience_state", "clue_source", "access", "surface_meaning", "true_meaning", "misread_reason", "reliability", "required_for_climax", "planted_scene_id", "verified_scene_id", "reveal_scene_id", "payoff_scene_id", "reveal_trigger", "action_consequence", "relationship_consequence"], label, errors)
            if isinstance(item, dict):
                truth_id = str(item.get("truth_id", ""))
                if truth_id in truth_ids:
                    errors.append(f"{label}: duplicate truth_id")
                truth_ids.add(truth_id)
                if not isinstance(item.get("required_for_climax"), bool):
                    errors.append(f"{label}: required_for_climax must be boolean")
                elif item.get("required_for_climax") is True:
                    decisive_count += 1
                planted, verified = item.get("planted_scene_id"), item.get("verified_scene_id")
                reveal, payoff = item.get("reveal_scene_id"), item.get("payoff_scene_id")
                if any(value not in scene_by_id for value in (planted, verified, reveal, payoff)):
                    errors.append(f"{label}: planted/verified/reveal/payoff scene must exist")
                elif not (scene_ids.index(planted) <= scene_ids.index(verified) <= scene_ids.index(reveal) <= scene_ids.index(payoff)):
                    errors.append(f"{label}: evidence order must be plant <= verify <= reveal <= payoff")
                if item.get("required_for_climax") is True:
                    climax_scene_id = data.get("climax_gate", {}).get("scene_id") if isinstance(data.get("climax_gate"), dict) else None
                    if climax_scene_id not in scene_by_id:
                        errors.append(f"{label}: cannot audit decisive clue without climax scene")
                    elif any(scene_ids.index(value) > scene_ids.index(climax_scene_id) for value in (verified, reveal) if value in scene_by_id) or (planted in scene_by_id and scene_ids.index(planted) >= scene_ids.index(climax_scene_id)):
                        errors.append(f"{label}: climax-required clue must be planted before and verified/revealed by climax")
        if suspense and decisive_count < 1:
            errors.append("suspense work requires at least one boolean climax-required clue")

    climax = data.get("climax_gate")
    required(climax, ["scene_id", "maximum_pressure", "core_dilemma", "protagonist_choice", "resource_ids", "resource_setup_scene_ids", "irreversible_cost", "opposition_result", "promise_ids_paid", "promise_payoff", "resulting_state_id", "world_after", "outcome_changes_without_protagonist"], "climax_gate", errors)
    if isinstance(climax, dict):
        climax_scene_id = climax.get("scene_id")
        if climax_scene_id not in scene_by_id:
            errors.append("climax_gate.scene_id must reference a scene")
        else:
            if climax.get("protagonist_choice") != scene_by_id[climax_scene_id].get("protagonist_choice"):
                errors.append("climax_gate.protagonist_choice must match climax scene")
        resource_ids = climax.get("resource_ids", []) or []
        setup_map = climax.get("resource_setup_scene_ids", {}) or {}
        if not isinstance(resource_ids, list) or not resource_ids or not isinstance(setup_map, dict):
            errors.append("climax resources must be ID-based and include setup-scene mapping")
        else:
            for resource_id in resource_ids:
                setup_scene = setup_map.get(resource_id)
                if setup_scene not in scene_by_id:
                    errors.append(f"climax resource setup scene missing: {resource_id}")
                elif climax_scene_id in scene_by_id and scene_ids.index(setup_scene) >= scene_ids.index(climax_scene_id):
                    errors.append(f"climax resource must be established before climax: {resource_id}")
                elif resource_id not in (scene_by_id[setup_scene].get("established_resource_ids", []) or []):
                    errors.append(f"climax resource not established by cited scene: {resource_id}")
        promise_ids = set(core.get("story_promises", {})) if isinstance(core, dict) and isinstance(core.get("story_promises"), dict) else set()
        paid_ids = set(climax.get("promise_ids_paid", []) or [])
        if not paid_ids or not paid_ids.issubset(promise_ids):
            errors.append("climax promise_ids_paid must reference frozen story promises")
        if climax_scene_id in scene_by_id:
            climax_scene = scene_by_id[climax_scene_id]
            if not paid_ids.issubset(set(climax_scene.get("paid_promise_ids", []) or [])):
                errors.append("climax scene must record paid promise IDs")
            if climax.get("resulting_state_id") != climax_scene.get("resulting_state_id"):
                errors.append("climax resulting_state_id must match climax scene")
        if climax.get("outcome_changes_without_protagonist") is not True:
            errors.append("climax must fail the protagonist-absence test: outcome_changes_without_protagonist must be true")
        if isinstance(dramaturgy, dict) and climax.get("protagonist_choice") != dramaturgy.get("climax_choice"):
            errors.append("climax_gate.protagonist_choice must match dramaturgy.climax_choice")

    ending = data.get("ending_contract")
    required(
        ending,
        [
            "emotional_result",
            "causal_closure",
            "revelation_mode",
            "structural_shape",
            "surface_result",
            "deep_result",
            "settlement",
            "protagonist_causality",
            "irreversible_cost",
            "theme_answer",
            "opening_echo_or_shape_evidence",
            "audience_afterimage",
            "promise_ids_paid",
        ],
        "ending_contract",
        errors,
    )
    if isinstance(ending, dict):
        if ending.get("emotional_result") not in ENDING_EMOTIONAL_RESULTS:
            errors.append("ending_contract.emotional_result is unsupported")
        if ending.get("causal_closure") not in ENDING_CAUSAL_CLOSURES:
            errors.append("ending_contract.causal_closure is unsupported")
        if ending.get("revelation_mode") not in ENDING_REVELATION_MODES:
            errors.append("ending_contract.revelation_mode is unsupported")
        if ending.get("structural_shape") not in ENDING_STRUCTURAL_SHAPES:
            errors.append("ending_contract.structural_shape is unsupported")
        if "open_debts" not in ending or not isinstance(ending.get("open_debts"), list):
            errors.append("ending_contract.open_debts must be a list")
        elif ending.get("causal_closure") == "OPEN" and not ending.get("open_debts"):
            errors.append("OPEN ending requires at least one explicit open debt")
        if ending.get("revelation_mode") == "FALSE_ENDING" and ending.get("surface_result") == ending.get("deep_result"):
            errors.append("FALSE_ENDING requires different surface_result and deep_result")

        settlement = ending.get("settlement")
        if not isinstance(settlement, dict):
            errors.append("ending_contract.settlement must be an object")
        else:
            missing_keys = ENDING_SETTLEMENT_KEYS - set(settlement)
            if missing_keys:
                errors.append(f"ending_contract.settlement missing dimensions: {sorted(missing_keys)}")
            for key in ENDING_SETTLEMENT_KEYS:
                item = settlement.get(key)
                required(item, ["status", "evidence_scene_id"], f"ending_contract.settlement.{key}", errors)
                if isinstance(item, dict):
                    if item.get("status") not in ENDING_SETTLEMENT_STATUSES:
                        errors.append(f"ending_contract.settlement.{key}.status is unsupported")
                    if item.get("evidence_scene_id") not in scene_by_id:
                        errors.append(f"ending_contract.settlement.{key}.evidence_scene_id must reference a scene")

        promise_ids = set(core.get("story_promises", {})) if isinstance(core, dict) and isinstance(core.get("story_promises"), dict) else set()
        ending_paid = ending.get("promise_ids_paid")
        if not isinstance(ending_paid, list) or not ending_paid or not set(ending_paid).issubset(promise_ids):
            errors.append("ending_contract.promise_ids_paid must reference frozen story promises")
        if isinstance(climax, dict):
            climax_paid = set(climax.get("promise_ids_paid", []) or [])
            if not climax_paid.issubset(set(ending_paid or [])):
                errors.append("ending_contract must carry forward every climax-paid promise")

    decision_registry = data.get("decision_registry")
    if not isinstance(decision_registry, dict) or not decision_registry:
        errors.append("decision_registry must be a non-empty object")
        decision_registry = {}
    else:
        for decision_id, decision in decision_registry.items():
            required(decision, ["owner", "status", "decision_hash"], f"decision_registry.{decision_id}", errors)
            if isinstance(decision, dict) and (decision.get("owner") != "CREATIVE_TO_NARRATIVE" or decision.get("status") != "APPROVED"):
                errors.append(f"decision_registry.{decision_id}: only Creative APPROVED decisions can authorize narrative layers")
    if isinstance(concept, dict) and str(concept.get("creative_decision_id", "")) not in decision_registry:
        errors.append("concept_contract.creative_decision_id must resolve to a Creative decision")

    known_truth_ids: set[str] = set()
    if isinstance(core, dict):
        known_truth_ids.add(str(core.get("core_id", "")))
        known_truth_ids.add(str(core.get("concept_id", "")))
        known_truth_ids |= set(map(str, (core.get("story_promises", {}) or {}).keys())) if isinstance(core.get("story_promises"), dict) else set()
    known_truth_ids |= {str(scene.get("resulting_state_id")) for scene in scenes if isinstance(scene, dict) and scene.get("resulting_state_id")}
    if isinstance(information, dict):
        known_truth_ids |= {str(item.get("truth_id")) for item in information.get("ledger", []) or [] if isinstance(item, dict) and item.get("truth_id")}

    receipts = data.get("layer_receipts")
    if not isinstance(receipts, list) or not receipts:
        errors.append("layer_receipts must be a non-empty list")
    else:
        known_layers = {str(source.get("narrative_ir_id", "")): ("NARRATIVE_IR", str(source.get("narrative_ir_version", "")), "VALIDATED")}
        seen_layer_ids: set[str] = set()
        pending_seen = False
        for idx, receipt in enumerate(receipts):
            label = f"layer_receipts[{idx}]"
            if not isinstance(receipt, dict):
                errors.append(f"{label}: must be an object")
                continue
            for key in ("layer_type", "layer_id", "status", "source_layer_id", "source_version", "output_version", "preserved_truth_ids", "transformed_field_ids", "proposed_story_changes", "creative_decision_id", "rejected_overrides"):
                if key not in receipt:
                    errors.append(f"{label}: missing {key}")
            layer_type, layer_id, status = receipt.get("layer_type"), str(receipt.get("layer_id", "")), receipt.get("status")
            source_layer_id = str(receipt.get("source_layer_id", ""))
            if layer_type not in LAYER_ORDER or layer_type == "NARRATIVE_IR":
                errors.append(f"{label}: unsupported output layer_type")
            if status not in LAYER_STATUSES:
                errors.append(f"{label}: unsupported status")
            if layer_id in seen_layer_ids or layer_id in known_layers:
                errors.append(f"{label}: duplicate layer_id")
            seen_layer_ids.add(layer_id)
            if source_layer_id not in known_layers:
                errors.append(f"{label}: source_layer_id does not exist")
            else:
                source_type, source_version, source_status = known_layers[source_layer_id]
                if source_status != "VALIDATED":
                    errors.append(f"{label}: upstream layer must be VALIDATED")
                if str(receipt.get("source_version")) != source_version:
                    errors.append(f"{label}: source_version mismatch")
                if layer_type in LAYER_ORDER and LAYER_ORDER[layer_type] != LAYER_ORDER[source_type] + 1:
                    errors.append(f"{label}: layer chain must advance exactly one compilation layer")
            if receipt.get("proposed_story_changes") and status != "PENDING_CREATIVE_REVIEW":
                errors.append(f"{label}: proposed story changes require PENDING_CREATIVE_REVIEW")
            if status == "PENDING_CREATIVE_REVIEW" and idx < len(receipts) - 1:
                errors.append(f"{label}: pending Creative review blocks later layers")
            if pending_seen:
                errors.append(f"{label}: no layer may follow pending Creative review")
            pending_seen = pending_seen or status == "PENDING_CREATIVE_REVIEW"
            if status == "VALIDATED":
                for key in ("layer_id", "output_version", "creative_decision_id", "preserved_truth_ids", "transformed_field_ids"):
                    if receipt.get(key) in (None, "", [], {}):
                        errors.append(f"{label}: VALIDATED receipt requires non-empty {key}")
                if str(receipt.get("creative_decision_id", "")) not in decision_registry:
                    errors.append(f"{label}: creative_decision_id does not resolve to decision_registry")
                for truth_id in receipt.get("preserved_truth_ids", []) or []:
                    if str(truth_id) not in known_truth_ids:
                        errors.append(f"{label}: preserved_truth_id is not registered: {truth_id}")
            known_layers[layer_id] = (str(layer_type), str(receipt.get("output_version", "")), str(status))

    output_state = data.get("output_state")
    required(output_state, ["cursor", "completed_units", "next_required_unit"], "output_state", errors)
    if isinstance(output_state, dict):
        completed = set(map(str, output_state.get("completed_units", []) or []))
        for receipt in receipts or []:
            if isinstance(receipt, dict) and receipt.get("status") == "VALIDATED" and str(receipt.get("layer_type")) not in completed:
                errors.append(f"validated layer missing from output_state.completed_units: {receipt.get('layer_type')}")
        pending_receipts = [item for item in receipts or [] if isinstance(item, dict) and item.get("status") == "PENDING_CREATIVE_REVIEW"]
        if pending_receipts:
            if output_state.get("next_required_unit") != "CREATIVE_DECISION" or output_state.get("cursor") not in {"PENDING_CREATIVE_REVIEW", "CREATIVE_DECISION_REQUIRED"}:
                errors.append("pending Creative review requires a blocking output_state cursor and CREATIVE_DECISION next unit")
        if isinstance(runtime, dict) and runtime.get("validation_mode") == "FORMAL_DELIVERY" and isinstance(task, dict):
            validated_layers = {str(item.get("layer_type")) for item in receipts or [] if isinstance(item, dict) and item.get("status") == "VALIDATED"}
            current_layers = set(map(str, task.get("current_delivery_layers", []) or []))
            goal_layers = set(map(str, task.get("project_goal_layers", []) or []))
            if not current_layers.issubset(validated_layers):
                errors.append("FORMAL_DELIVERY current_delivery_layers must all have VALIDATED receipts")
            if task.get("delivery_scope") == "FINAL" and not goal_layers.issubset(validated_layers):
                errors.append("FINAL delivery must validate every project_goal_layer")
    return errors, warnings


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()
    try:
        data = load_document(args.input)
        errors, warnings = validate(data)
    except Exception as exc:
        errors, warnings = [f"load failure: {exc}"], []
    result = {"status": "PASS" if not errors else "FAIL", "errors": errors, "warnings": warnings}
    print(json.dumps(result, ensure_ascii=False, indent=2) if args.json else "\n".join([result["status"], *[f"ERROR: {e}" for e in errors], *[f"WARN: {w}" for w in warnings]]))
    return 0 if not errors else 1


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