#!/usr/bin/env python3
"""Validate the PRISM screenplay-production control plan."""

from __future__ import annotations

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

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


STAGES = {f"W{i}": i for i in range(13)}
ENTRY_MODES = {
    "FROM_SEED", "FROM_STORY", "REWRITE_SCREENPLAY", "SCRIPT_DOCTOR",
    "DIALOGUE_PERFORMANCE_PATCH", "TO_DIRECTOR_SCRIPT", "TO_ATOMIC_VIDEO",
    "REFERENCE_REVERSE_COMPILE",
}
OUTPUT_LAYERS = {"STORY_BLUEPRINT", "SCREENPLAY", "DIRECTOR_SHOOTING_SCRIPT", "ATOMIC_VIDEO_PACKAGE", "AUDIT"}
CAPABILITIES = {
    "CREATIVE_TO_NARRATIVE", "SCREENPLAY_CRAFT", "PRISM_MASTER_DIRECTOR",
    "CREATIVE_MEDIA_RENDERER", "SHANYIN_DELTA_ONLY", "JIMENG_PERFORMANCE_OPERATOR",
    "MIRROR_COMPOSITION_SUPPORT", "PROP_CONTINUITY_SUPPORT", "SCENE_BLOCKING_CONTROL",
    "CAUSAL_COMBAT_SYSTEM", "REVERSE_COMPILE_RUNES", "PLATFORM_ADAPTER",
    "CONTINUITY_GATE", "EVALUATION_GATE",
}
ARTIFACT_TYPES = {
    "TASK_CONTRACT", "SOURCE_LEDGER", "CONCEPT_CONTRACT", "FROZEN_STORY_CORE",
    "PRISM-NARRATIVE-IR-1.1", "SCENE_LIFE_CONTRACT", "SCREENPLAY_CRAFT_CONTRACT",
    "PRISM-SCREENPLAY-IR-1.0", "SPATIAL_CONTINUITY_LEDGER", "PRISM-DIRECTOR-IR-1.0",
    "ATOMIC_VIDEO_PACKAGE", "VALIDATION_RECEIPT", "DELTA_PATCH", "CHECKPOINT",
}
STATUSES = {"PENDING", "ACTIVE", "VALIDATED", "SKIPPED_WITH_RECEIPT", "BLOCKED"}
ARTIFACT_STATUSES = {"PENDING", "ACTIVE", "VALIDATED", "REJECTED", "BLOCKED"}


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


def nonempty(value: Any) -> bool:
    return isinstance(value, str) and bool(value.strip())


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

    if data.get("schema_version") != "PRISM-WORKFLOW-PLAN-1.0":
        errors.append("schema_version must be PRISM-WORKFLOW-PLAN-1.0")
    for key in ("project_id", "workflow_version"):
        if not nonempty(data.get(key)):
            errors.append(f"{key} must be non-empty")

    authority = data.get("authority")
    if not isinstance(authority, dict):
        errors.append("authority must be an object")
    else:
        if authority.get("controller_count") != 1:
            errors.append("authority.controller_count must equal 1")
        if authority.get("global_controller") not in {"WANFU", "PRISM_STANDALONE"}:
            errors.append("authority.global_controller is unsupported")
        if authority.get("narrative_truth_owner") != "CREATIVE_TO_NARRATIVE":
            errors.append("authority.narrative_truth_owner must be CREATIVE_TO_NARRATIVE")

    if data.get("entry_mode") not in ENTRY_MODES:
        errors.append("entry_mode is unsupported")
    output_layer = data.get("requested_output_layer")
    if output_layer not in OUTPUT_LAYERS:
        errors.append("requested_output_layer is unsupported")
    current = data.get("current_stage")
    target = data.get("target_stage")
    if current not in STAGES:
        errors.append("current_stage is unsupported")
    if target not in STAGES:
        errors.append("target_stage is unsupported")
    if current in STAGES and target in STAGES and STAGES[current] > STAGES[target]:
        errors.append("current_stage cannot be later than target_stage")

    runtime = data.get("runtime_load")
    if not isinstance(runtime, dict):
        errors.append("runtime_load must be an object")
    else:
        primary = runtime.get("primary_capability")
        auxiliaries = runtime.get("active_auxiliaries")
        if primary not in CAPABILITIES:
            errors.append("runtime_load.primary_capability is unsupported")
        if not isinstance(auxiliaries, list):
            errors.append("runtime_load.active_auxiliaries must be a list")
        else:
            if len(auxiliaries) > 2:
                errors.append("runtime_load active auxiliary budget exceeds two")
            if len(auxiliaries) != len(set(auxiliaries)):
                errors.append("runtime_load.active_auxiliaries contains duplicates")
            for item in auxiliaries:
                if item not in CAPABILITIES:
                    errors.append(f"unsupported active auxiliary capability: {item}")
                if item == primary:
                    errors.append("primary capability cannot also be an active auxiliary")
        if runtime.get("compression_target") != "ONE_FINAL_RENDER":
            errors.append("runtime_load.compression_target must be ONE_FINAL_RENDER")

    artifacts = data.get("artifacts")
    artifact_map: dict[str, dict[str, Any]] = {}
    if not isinstance(artifacts, list) or not artifacts:
        errors.append("artifacts must be a non-empty list")
    else:
        for idx, artifact in enumerate(artifacts):
            prefix = f"artifacts[{idx}]"
            if not isinstance(artifact, dict):
                errors.append(f"{prefix} must be an object")
                continue
            artifact_id = artifact.get("artifact_id")
            if not nonempty(artifact_id):
                errors.append(f"{prefix}.artifact_id must be non-empty")
                continue
            if artifact_id in artifact_map:
                errors.append(f"duplicate artifact_id: {artifact_id}")
            artifact_map[artifact_id] = artifact
            if artifact.get("artifact_type") not in ARTIFACT_TYPES:
                errors.append(f"{prefix}.artifact_type is unsupported")
            if not nonempty(artifact.get("owner")):
                errors.append(f"{prefix}.owner must be non-empty")
            if artifact.get("status") not in ARTIFACT_STATUSES:
                errors.append(f"{prefix}.status is unsupported")

    stages = data.get("stage_plan")
    stage_ids: set[str] = set()
    active_count = 0
    if not isinstance(stages, list) or not stages:
        errors.append("stage_plan must be a non-empty list")
    else:
        last_order = -1
        for idx, stage in enumerate(stages):
            prefix = f"stage_plan[{idx}]"
            if not isinstance(stage, dict):
                errors.append(f"{prefix} must be an object")
                continue
            stage_id = stage.get("stage_id")
            if stage_id not in STAGES:
                errors.append(f"{prefix}.stage_id is unsupported")
                continue
            if stage_id in stage_ids:
                errors.append(f"duplicate stage_id: {stage_id}")
            stage_ids.add(stage_id)
            if STAGES[stage_id] < last_order:
                errors.append("stage_plan must be ordered by stage")
            last_order = STAGES[stage_id]
            status = stage.get("status")
            if status not in STATUSES:
                errors.append(f"{prefix}.status is unsupported")
            active_count += status == "ACTIVE"
            if not nonempty(stage.get("owner")):
                errors.append(f"{prefix}.owner must be non-empty")
            rollback = stage.get("rollback_stage")
            if rollback not in STAGES or STAGES[rollback] > STAGES[stage_id]:
                errors.append(f"{prefix}.rollback_stage must resolve to this or an earlier stage")
            for field in ("input_artifact_ids", "output_artifact_ids", "gate_ids"):
                values = stage.get(field)
                if not isinstance(values, list):
                    errors.append(f"{prefix}.{field} must be a list")
                    continue
                if field != "gate_ids":
                    for artifact_id in values:
                        if artifact_id not in artifact_map:
                            errors.append(f"{prefix}.{field} references unknown artifact: {artifact_id}")
        if active_count > 1:
            errors.append("stage_plan can contain at most one ACTIVE stage")
        if current in STAGES and current not in stage_ids:
            errors.append("current_stage must appear in stage_plan")
        if target in STAGES and target not in stage_ids:
            errors.append("target_stage must appear in stage_plan")

    artifact_types = {a.get("artifact_type") for a in artifact_map.values()}
    validated_types = {a.get("artifact_type") for a in artifact_map.values() if a.get("status") == "VALIDATED"}
    required_output = {
        "STORY_BLUEPRINT": "PRISM-NARRATIVE-IR-1.1",
        "SCREENPLAY": "PRISM-SCREENPLAY-IR-1.0",
        "DIRECTOR_SHOOTING_SCRIPT": "PRISM-DIRECTOR-IR-1.0",
        "ATOMIC_VIDEO_PACKAGE": "ATOMIC_VIDEO_PACKAGE",
    }.get(output_layer)
    if required_output and required_output not in artifact_types:
        errors.append(f"requested output requires artifact type {required_output}")
    if output_layer in {"SCREENPLAY", "DIRECTOR_SHOOTING_SCRIPT", "ATOMIC_VIDEO_PACKAGE"} and "PRISM-NARRATIVE-IR-1.1" not in validated_types:
        errors.append("downstream delivery requires a VALIDATED PRISM-NARRATIVE-IR-1.1 source")
    if output_layer in {"DIRECTOR_SHOOTING_SCRIPT", "ATOMIC_VIDEO_PACKAGE"} and "PRISM-SCREENPLAY-IR-1.0" not in validated_types:
        errors.append("director or video delivery requires a VALIDATED PRISM-SCREENPLAY-IR-1.0 source")
    if output_layer == "ATOMIC_VIDEO_PACKAGE" and "PRISM-DIRECTOR-IR-1.0" not in validated_types:
        errors.append("atomic video delivery requires a VALIDATED PRISM-DIRECTOR-IR-1.0 source")

    receipts = data.get("layer_receipts")
    if not isinstance(receipts, list):
        errors.append("layer_receipts must be a list")
    else:
        receipt_ids: set[str] = set()
        for idx, receipt in enumerate(receipts):
            prefix = f"layer_receipts[{idx}]"
            if not isinstance(receipt, dict):
                errors.append(f"{prefix} must be an object")
                continue
            receipt_id = receipt.get("receipt_id")
            if not nonempty(receipt_id):
                errors.append(f"{prefix}.receipt_id must be non-empty")
            elif receipt_id in receipt_ids:
                errors.append(f"duplicate receipt_id: {receipt_id}")
            receipt_ids.add(receipt_id)
            output_id = receipt.get("output_artifact_id")
            if output_id not in artifact_map:
                errors.append(f"{prefix}.output_artifact_id does not resolve")
            sources = receipt.get("source_artifact_ids")
            if not isinstance(sources, list) or any(item not in artifact_map for item in sources):
                errors.append(f"{prefix}.source_artifact_ids must resolve")
            if receipt.get("status") == "VALIDATED" and not nonempty(receipt.get("creative_decision_id")):
                errors.append(f"{prefix} VALIDATED receipt requires creative_decision_id")

    validation_plan = data.get("validation_plan")
    if not isinstance(validation_plan, list) or not validation_plan:
        errors.append("validation_plan must be a non-empty list")
    else:
        if output_layer == "SCREENPLAY" and "STATIC_SCREENPLAY_VALIDATOR" not in validation_plan:
            errors.append("SCREENPLAY delivery requires STATIC_SCREENPLAY_VALIDATOR")
        if output_layer in {"DIRECTOR_SHOOTING_SCRIPT", "ATOMIC_VIDEO_PACKAGE"} and "STATIC_DIRECTOR_VALIDATOR" not in validation_plan:
            errors.append("director/video delivery requires STATIC_DIRECTOR_VALIDATOR")

    if not isinstance(data.get("unverified_claims"), list):
        errors.append("unverified_claims must be a list")

    return errors, warnings


def main() -> int:
    if len(sys.argv) != 2:
        print("usage: validate_workflow_plan.py path/to/workflow-plan.yaml", file=sys.stderr)
        return 2
    try:
        data = load_document(Path(sys.argv[1]))
        errors, warnings = validate(data)
    except Exception as exc:
        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())
