#!/usr/bin/env python3
from __future__ import annotations
import copy, json, sys
from pathlib import Path

REQUIRED_MODULES = {"NOVEL_GENRE_AUX","DIALOGUE_SUBTEXT_AUX","CREATIVE_FORGE_AUX","LIVENESS_RED_TEAM","SHORT_DRAMA_MEDIA_DELTA"}
FORBIDDEN_STORY_FIELDS = {"story_truth","plot","character_choice","scene_outcome"}
DIALOGUE_PRECONDITIONS = {
    "scene_event_locked","immediate_goal_locked","relationship_position_locked",
    "knowledge_permission_locked","unsayable_content_locked","exit_state_locked"
}

def validate(doc: dict) -> tuple[list[str], list[str]]:
    errors=[]; warnings=[]
    if doc.get("controller") != "juben": errors.append("controller must remain juben")
    if doc.get("controller_count") != 1: errors.append("controller_count must equal 1")
    if doc.get("narrative_truth_owner") != "CREATIVE_TO_NARRATIVE": errors.append("narrative truth owner must remain CREATIVE_TO_NARRATIVE")
    if doc.get("creates_new_ir") is not False: errors.append("auxiliary integration must not create a new IR")
    if doc.get("active_auxiliaries_max") != 2: errors.append("active auxiliary budget must remain two")
    modules = doc.get("modules")
    if not isinstance(modules, list): return errors+["modules must be a list"], warnings
    by_id={m.get("id"):m for m in modules if isinstance(m,dict)}
    missing=REQUIRED_MODULES-set(by_id)
    if missing: errors.append("missing required auxiliary modules: "+", ".join(sorted(missing)))
    novel=by_id.get("NOVEL_GENRE_AUX",{})
    if novel.get("role") != "PASSIVE_REFERENCE": errors.append("novel knowledge base must remain PASSIVE_REFERENCE")
    if set(novel.get("allowed_fields",[])) & FORBIDDEN_STORY_FIELDS: errors.append("novel knowledge base cannot own story fields")
    dialogue=by_id.get("DIALOGUE_SUBTEXT_AUX",{})
    if dialogue.get("role") != "LATE_STAGE_AUXILIARY": errors.append("dialogue knowledge base must remain LATE_STAGE_AUXILIARY")
    if not DIALOGUE_PRECONDITIONS.issubset(set(dialogue.get("preconditions",[]))): errors.append("dialogue auxiliary is missing locked-scene preconditions")
    forge=by_id.get("CREATIVE_FORGE_AUX",{})
    if forge.get("role") != "CANDIDATE_GENERATOR": errors.append("Creative Forge must remain a candidate generator")
    if forge.get("requires_creative_decision") is not True: errors.append("Creative Forge output requires Creative decision")
    red=by_id.get("LIVENESS_RED_TEAM",{})
    if red.get("role") != "AUDIT_ONLY": errors.append("liveness red team must remain audit-only")
    short=by_id.get("SHORT_DRAMA_MEDIA_DELTA",{})
    if short.get("role") != "MEDIA_ADAPTER": errors.append("short-drama delta must remain MEDIA_ADAPTER")
    if short.get("requires_juben_story_truth") is not True: errors.append("short-drama delta requires juben story truth")
    if short.get("counts_toward_active_auxiliary_budget") is not True: errors.append("short-drama delta must count toward auxiliary budget")
    if set(short.get("allowed_fields",[])) & FORBIDDEN_STORY_FIELDS: errors.append("short-drama delta cannot own story fields")
    if short.get("hard_fixed_scene_count") is not False: errors.append("short-drama delta cannot force a fixed scene count")
    if short.get("twist_required") is not False: errors.append("short-drama delta cannot require a twist")
    if "JUBEN Runtime Router v1.0" not in doc.get("retired_primary_routers",[]): errors.append("temporary runtime router must be retired as primary")
    claims=doc.get("release_claims",{})
    if claims.get("better_than_old_version_requires") != "COMPARATIVE_BLIND_TESTED": errors.append("better-than-old claim requires comparative blind test")
    if claims.get("professional_pass_requires") != "HUMAN_REVIEWED": errors.append("professional-pass claim requires human review")
    return errors,warnings

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

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