#!/usr/bin/env python3
"""Validate JINGHUA longform project-memory and prose preservation contract."""
from __future__ import annotations
import json, sys
from pathlib import Path
from typing import Any

REQUIRED_ARTIFACTS = {
    "00_NODE_RECEIPT.json","01_30秒前情.md","02_标准前情.md","03_深度恢复.md",
    "04_EVENT_TIMELINE.json","05_CHARACTER_STATE.json","06_KNOWLEDGE_PERMISSIONS.json",
    "07_PROMISE_LEDGER.json","08_WORLD_RELATION_STATE.json","09_REFERENCE_CONSUMPTION.json",
    "10_SOURCE_REMAINDER_VIEW.md","11_NEXT_NODE_SEED.json","12_CHANGE_IMPACT.json","13_NODE_MANIFEST.json",
}
OPEN_PROMISE_STATES={"ACTIVE","PARTIAL_PAYOFF"}
VALID_NODE_STATES={"DRAFT","VALIDATED","STALE","SUPERSEDED","ARCHIVED"}


def validate(doc: dict[str,Any]) -> list[str]:
    e=[]
    if doc.get("schema_version") != "JINGHUA-LONGFORM-1.0": e.append("schema_version must equal JINGHUA-LONGFORM-1.0")
    if doc.get("mode") != "LONGFORM_PROJECT": e.append("mode must equal LONGFORM_PROJECT")
    a=doc.get("authority",{})
    if a.get("controller") != "juben": e.append("controller must remain juben")
    if a.get("longform_truth_artifact") != "ORIGINAL_NOVEL_IR": e.append("longform truth must be ORIGINAL_NOVEL_IR")
    if a.get("simultaneous_story_truth_owners") is not False: e.append("simultaneous story truth owners are forbidden")
    if a.get("screenplay_ir_active") is True: e.append("screenplay NARRATIVE_IR must not be active during longform production")
    if not a.get("jingyuan_available") and not a.get("compatibility_mode"): e.append("longform requires JINGYUAN or compatibility mode")

    p=doc.get("project",{})
    if p.get("current_node_status") not in VALID_NODE_STATES: e.append("invalid current node status")
    if p.get("current_node_status") != "VALIDATED" and p.get("official_canon_allowed"): e.append("OFFICIAL_CANON requires VALIDATED current node")
    if not p.get("latest_validated_main_node"): e.append("latest validated main node is required")

    pf=doc.get("preflight",{})
    required_pf=["truth_source_locked","outline_card_loaded","latest_validated_node_loaded","character_state_loaded","knowledge_permissions_loaded","active_promises_loaded","resource_physical_state_loaded","relationship_address_state_loaded","antagonist_offscreen_plan_loaded","world_state_loaded"]
    for k in required_pf:
        if pf.get(k) is not True: e.append(f"preflight missing or false: {k}")
    if pf.get("stale_blockers"): e.append("STALE blockers must stop continuation")
    if pf.get("write_status") == "OFFICIAL_CANON" and any(pf.get(k) is not True for k in required_pf): e.append("OFFICIAL_CANON preflight incomplete")

    arts=set(doc.get("required_artifacts",[]))
    miss=REQUIRED_ARTIFACTS-arts
    if miss: e.append("missing node dossier artifacts: "+", ".join(sorted(miss)))

    mem=doc.get("memory_lifecycle",{})
    for k in ["permanent_memory_present","active_memory_present","dormant_archive_present","contamination_isolation_present"]:
        if mem.get(k) is not True: e.append(f"memory lifecycle missing {k}")
    if mem.get("contamination_loaded_during_normal_prose") is not False: e.append("contamination isolation memory must not load during normal prose")
    if mem.get("forgetting_means_delete_history") is not False: e.append("forgetting must archive, not delete history")

    eh=doc.get("event_history",{})
    if eh.get("event_ids_stable") is not True: e.append("event ids must remain stable")
    if eh.get("revised_events_preserve_audit_trail") is not True: e.append("revised events must preserve audit trail")
    if eh.get("void_events_preserve_audit_trail") is not True: e.append("void events must preserve audit trail")
    if eh.get("renumber_after_revision") is not False: e.append("event renumber after revision is forbidden")

    rec=doc.get("recaps",{})
    for k in ["brief_present","standard_present","deep_present"]:
        if rec.get(k) is not True: e.append(f"recap missing: {k}")
    if rec.get("recap_replaces_ledgers") is not False: e.append("recaps must not replace ledgers")

    chars=doc.get("characters",[])
    if not chars: e.append("character state ledger must not be empty")
    for c in chars:
        for k in ["current_location","physical_state","known_facts","unknown_facts","false_beliefs","resources","lost_resources","forbidden_auto_recovery","next_plan"]:
            if k not in c: e.append(f"character state missing {k}")
        lost=set(c.get("lost_resources",[])); forbidden=set(c.get("forbidden_auto_recovery",[]))
        if lost and not lost.issubset(forbidden): e.append("lost resources must be protected from auto recovery")

    for pr in doc.get("promises",[]):
        if pr.get("status") in OPEN_PROMISE_STATES and pr.get("in_next_seed") is not True:
            e.append("ACTIVE/PARTIAL_PAYOFF promise must enter NEXT_NODE_SEED")
    seed=doc.get("next_node_seed",{})
    for k in ["current_story_time","current_locations","character_states_ref","knowledge_permissions_ref","active_promises_ref","active_antagonist_plan","irreversible_changes","forbidden_regressions","relationship_and_address_pressure","resource_and_physical_constraints","next_node_main_task"]:
        if k not in seed or seed.get(k) in (None,""): e.append(f"NEXT_NODE_SEED missing {k}")

    rc=doc.get("recovery_context",{})
    for k in ["load_original_novel_ir","load_current_volume_or_arc","load_latest_validated_main_node","load_next_node_seed"]:
        if rc.get(k) is not True: e.append(f"recovery context missing {k}")
    if rc.get("full_manuscript_dump") is not False: e.append("full manuscript dump is forbidden by default")
    if rc.get("all_abandoned_plans_loaded") is not False: e.append("abandoned plans must not be loaded by default")

    ci=doc.get("change_impact",{})
    if ci.get("stale_nodes") and ci.get("current_node_legal") is True: e.append("current node cannot remain legal when stale dependencies exist")
    if ci.get("retroactive_change") and not ci.get("required_rebuilds"): e.append("retroactive changes require rebuild targets")

    st=doc.get("source_track",{})
    if st.get("has_reference_source"):
        for k in ["source_master_immutable","source_master_sha256_present","actual_ranges_recorded","consumption_ledger_present","remainder_view_present"]:
            if st.get(k) is not True: e.append(f"reference source track missing {k}")
        if st.get("consumed_means_copy_permission") is not False: e.append("CONSUMED must not mean copy permission")


    cov=doc.get("source_coverage",{})
    if st.get("has_reference_source"):
        for k in ["actual_ranges_read_present","coverage_limit_present","unread_or_unproven_present"]:
            if cov.get(k) is not True: e.append(f"source coverage missing {k}")
        if cov.get("claims_full_book_without_full_coverage") is not False: e.append("full-book analysis claim requires full coverage evidence")
        if cov.get("guess_range_when_unanchored") is not False: e.append("source ranges must not be guessed when unanchored")

    batch=doc.get("batch",{})
    if batch.get("fixed_one_chapter_global_rule") is not False: e.append("fixed one-chapter global rule is forbidden")
    if batch.get("fixed_chapter_length_global_rule") is not False: e.append("fixed chapter-length global rule is forbidden")
    if batch.get("multi_chapter_requires_frozen_micro_arc") is not True: e.append("multi-chapter batches require frozen micro arc")
    if batch.get("per_chapter_commit_required") is not True: e.append("multi-chapter output still requires per-chapter commit")

    pre=doc.get("preproduction",{})
    for k in ["truth_frozen","volume_goal_present","character_ecology_present","relationship_state_present","address_permissions_present","antagonist_independent_plan_present","resource_knowledge_promise_ledgers_initialized"]:
        if pre.get(k) is not True: e.append(f"preproduction missing {k}")
    if pre.get("hard_fixed_character_count") is not False: e.append("hard fixed character count is forbidden")
    if pre.get("hard_fixed_total_chapters") is not False: e.append("hard fixed total chapter count is forbidden")


    sc=doc.get("scene_card",{})
    for k in ["pov_present","entry_state_present","resistance_present","knowledge_permissions_present","relationship_positions_present","addresses_allowed_present","exit_state_present"]:
        if sc.get(k) is not True: e.append(f"longform scene card missing {k}")
    if sc.get("dominant_image_required") is not False: e.append("scene card dominant image must remain optional")

    canon=doc.get("canon_status",{})
    if canon.get("status") not in {"CONCEPT","PROBE","OFFICIAL_CANON"}: e.append("invalid canon status")
    if canon.get("probe_auto_promoted") is not False: e.append("PROBE must not auto-promote to OFFICIAL_CANON")
    if canon.get("probe_merge_requires_change_receipt") is not True: e.append("PROBE merge requires change receipt")

    prose=doc.get("prose",{})
    if prose.get("medium") != "FICTION_NOVEL": e.append("novel prose runtime must remain FICTION_NOVEL")
    if prose.get("pov_position_card_present") is not True: e.append("POV position card is required")
    if prose.get("paragraph_carrier_ledger_used_postdraft") is not True: e.append("paragraph carrier audit must exist post-draft")
    if prose.get("dominant_image_is_optional") is not True: e.append("dominant image must remain optional")
    if prose.get("seven_pass_revision_is_postdraft") is not True: e.append("seven-pass revision must be post-draft")
    if prose.get("screenplay_triangle_format_required") is not False: e.append("screenplay triangle format must not leak into novel prose")
    if prose.get("audit_profile") != "FICTION_NOVEL": e.append("longform prose audit profile must be FICTION_NOVEL")
    if prose.get("one_rule_set_for_all_media") is not False: e.append("one prose audit rule set for all media is forbidden")
    if prose.get("compression_test_is_diagnostic_only") is not True: e.append("compression test must remain diagnostic only")

    reader=doc.get("reader_state",{})
    for k in ["confirmed_facts_present","intended_misreadings_present","unanswered_questions_present","promises_expected_present","reader_state_survives_node_recovery"]:
        if reader.get(k) is not True: e.append(f"reader state missing {k}")
    if reader.get("reader_info_equals_character_info") is not False: e.append("reader knowledge must not be collapsed into character knowledge")

    nv=doc.get("narrative_voice",{})
    for k in ["style_bible_present","pov_distance_defined","diction_range_defined","rhythm_range_defined","allowed_evolution_by_arc"]:
        if nv.get(k) is not True: e.append(f"narrative voice state missing {k}")
    if nv.get("fixed_catchphrase_as_voice_lock") is not False: e.append("narrative voice must not be reduced to fixed catchphrases")

    rg=doc.get("reality_grounding",{})
    if rg.get("real_world_claim_strength") in {"MIXED","HIGH"}:
        if rg.get("uncertain_claims_marked") is not True: e.append("uncertain real-world claims must be marked")
        if rg.get("fictionalized_departures_declared") is not True: e.append("fictionalized departures must be declared when reality contract is strong")
    if rg.get("unsupported_specific_fact_as_verified") is not False: e.append("unsupported specific fact cannot be presented as verified")

    pw=doc.get("postwrite",{})
    for k in ["event_ledger_updated","character_state_updated","knowledge_permissions_updated","resource_physical_state_updated","relationship_address_state_updated","promise_ledger_updated","antagonist_offscreen_action_updated","world_state_updated","next_node_seed_updated"]:
        if pw.get(k) is not True: e.append(f"postwrite commit missing {k}")
    if pw.get("uncommitted_draft") is True: e.append("uncommitted draft cannot be official continuation state")
    if pw.get("per_chapter_commit_present") is not True: e.append("per-chapter state commit is required")
    if pw.get("multi_chapter_batch_single_final_commit_only") is not False: e.append("multi-chapter batch cannot use only one final state commit")

    sen=doc.get("sentinel",{})
    if sen.get("machine_receipt_present") is not True: e.append("machine-level novel batch receipt is required")
    if sen.get("legacy_visible_sentinel_enabled") and sen.get("legacy_visible_sentinel_text") != "亲爱的兄弟": e.append("legacy visible sentinel must exactly equal 亲爱的兄弟")

    h=doc.get("handoff",{})
    if h.get("screenplay_requested"):
        if h.get("novel_snapshot_frozen_before_screenplay") is not True: e.append("screenplay handoff requires frozen novel snapshot")
        if h.get("narrative_ir_derived_after_snapshot") is not True: e.append("NARRATIVE_IR must derive after novel snapshot")

    claims=doc.get("release_claims",{})
    if claims.get("human_literary_reviewed") is True: e.append("static longform contract cannot claim HUMAN_LITERARY_REVIEWED")
    if claims.get("million_word_continuity_proven") is True: e.append("static longform contract cannot claim million-word continuity proven")
    if claims.get("zero_omission_guaranteed") is True: e.append("zero omission guarantee is forbidden")
    return e


def main()->int:
    path=Path(sys.argv[1] if len(sys.argv)>1 else "references/longform-preservation-test-fixture.json")
    doc=json.loads(path.read_text(encoding="utf-8"))
    errors=validate(doc)
    print(json.dumps({"status":"PASS" if not errors else "FAIL","errors":errors},ensure_ascii=False,indent=2))
    return 0 if not errors else 1

if __name__=="__main__": raise SystemExit(main())
