﻿#!/usr/bin/env python3
"""Validate the CONTENT_GAP_REPAIR decision and regression closure."""

from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import Any


SEVERITIES = {"BLOCK", "MAJOR", "MINOR", "OPTIONAL"}
PATCH_MODES = {"CONSERVATIVE", "STRUCTURAL", "BOLD"}
FACT_BUCKETS = {"explicit_facts", "strong_inferences", "open_slots", "contradictions"}
REGRESSION_KEYS = {
    "hard_locks_preserved",
    "causal_chain_preserved",
    "character_agency_preserved",
    "information_permissions_preserved",
    "promise_payoff_status",
    "continuity_status",
    "duration_capacity_status",
    "new_contradictions",
    "unresolved_gaps",
}


def nonempty_string(value: Any) -> bool:
    return isinstance(value, str) and bool(value.strip())


def validate(document: Any) -> tuple[list[str], list[str]]:
    errors: list[str] = []
    warnings: list[str] = []
    if not isinstance(document, dict):
        return ["document must be an object"], warnings
    if document.get("schema_version") != "JUBEN-CONTENT-GAP-1.0":
        errors.append("schema_version must be JUBEN-CONTENT-GAP-1.0")

    request = document.get("request_contract")
    if not isinstance(request, dict):
        errors.append("request_contract must be an object")
        request = {}
    if request.get("entry_mode") not in {"CONTENT_GAP_REPAIR", "SCRIPT_DOCTOR"}:
        errors.append("request_contract.entry_mode is unsupported")
    if not nonempty_string(request.get("source_id")) or not nonempty_string(request.get("source_version")):
        errors.append("request_contract requires source_id and source_version")
    if not nonempty_string(request.get("output_layer")):
        errors.append("request_contract requires output_layer")
    if not isinstance(request.get("allowed_changes"), list) or not request.get("allowed_changes"):
        errors.append("request_contract.allowed_changes must be a non-empty list")

    locks = document.get("freeze_manifest")
    hard_lock_ids: set[str] = set()
    if not isinstance(locks, list) or not locks:
        errors.append("freeze_manifest must be a non-empty list")
        locks = []
    seen_locks: set[str] = set()
    for index, lock in enumerate(locks):
        label = f"freeze_manifest[{index}]"
        if not isinstance(lock, dict):
            errors.append(f"{label} must be an object")
            continue
        lock_id = lock.get("lock_id")
        if not nonempty_string(lock_id):
            errors.append(f"{label} missing lock_id")
        elif lock_id in seen_locks:
            errors.append(f"{label} duplicate lock_id {lock_id}")
        else:
            seen_locks.add(lock_id)
            if lock.get("strength") == "HARD":
                hard_lock_ids.add(lock_id)
        if lock.get("strength") not in {"HARD", "SOFT"}:
            errors.append(f"{label} strength must be HARD or SOFT")
        if lock.get("change_requires") not in {"USER_APPROVAL", "CREATIVE_DECISION", "LOCAL_PATCH"}:
            errors.append(f"{label} has unsupported change_requires")

    partition = document.get("evidence_partition")
    if not isinstance(partition, dict):
        errors.append("evidence_partition must be an object")
        partition = {}
    for bucket in sorted(FACT_BUCKETS):
        if not isinstance(partition.get(bucket), list):
            errors.append(f"evidence_partition.{bucket} must be a list")

    gaps = document.get("gap_map")
    if not isinstance(gaps, list) or not gaps:
        errors.append("gap_map must be a non-empty list")
        gaps = []
    gap_ids: set[str] = set()
    major_gap_ids: set[str] = set()
    for index, gap in enumerate(gaps):
        label = f"gap_map[{index}]"
        if not isinstance(gap, dict):
            errors.append(f"{label} must be an object")
            continue
        gap_id = gap.get("gap_id")
        if not nonempty_string(gap_id):
            errors.append(f"{label} missing gap_id")
        elif gap_id in gap_ids:
            errors.append(f"{label} duplicate gap_id {gap_id}")
        else:
            gap_ids.add(gap_id)
        severity = gap.get("severity")
        if severity not in SEVERITIES:
            errors.append(f"{label} has unsupported severity")
        elif severity in {"BLOCK", "MAJOR"} and nonempty_string(gap_id):
            major_gap_ids.add(gap_id)
        if not gap.get("source_evidence"):
            errors.append(f"{label} requires source_evidence")
        if not nonempty_string(gap.get("nearest_legal_rollback")):
            errors.append(f"{label} requires nearest_legal_rollback")

    patches = document.get("patch_options")
    if not isinstance(patches, list) or not patches:
        errors.append("patch_options must be a non-empty list")
        patches = []
    patch_ids: set[str] = set()
    by_gap: dict[str, list[dict[str, Any]]] = {}
    for index, patch in enumerate(patches):
        label = f"patch_options[{index}]"
        if not isinstance(patch, dict):
            errors.append(f"{label} must be an object")
            continue
        patch_id = patch.get("patch_id")
        if not nonempty_string(patch_id):
            errors.append(f"{label} missing patch_id")
        elif patch_id in patch_ids:
            errors.append(f"{label} duplicate patch_id {patch_id}")
        else:
            patch_ids.add(patch_id)
        if patch.get("mode") not in PATCH_MODES:
            errors.append(f"{label} has unsupported mode")
        refs = patch.get("gap_refs")
        if not isinstance(refs, list) or not refs:
            errors.append(f"{label} requires gap_refs")
            refs = []
        for gap_ref in refs:
            if gap_ref not in gap_ids:
                errors.append(f"{label} references unknown gap {gap_ref}")
            by_gap.setdefault(gap_ref, []).append(patch)
        if not isinstance(patch.get("proposed_delta"), dict) or not patch.get("proposed_delta"):
            errors.append(f"{label} requires a non-empty proposed_delta")
        preserved = set(patch.get("preserved_locks") or [])
        if not hard_lock_ids.issubset(preserved):
            errors.append(f"{label} does not preserve every HARD lock")
        if not nonempty_string(patch.get("rollback_point")):
            errors.append(f"{label} requires rollback_point")

    for gap_id in sorted(major_gap_ids):
        candidates = by_gap.get(gap_id, [])
        if not 2 <= len(candidates) <= 3:
            errors.append(f"major gap {gap_id} requires two or three patch candidates")
            continue
        if not any(candidate.get("mode") == "CONSERVATIVE" for candidate in candidates):
            errors.append(f"major gap {gap_id} requires a CONSERVATIVE patch")
        deltas = {json.dumps(candidate.get("proposed_delta"), ensure_ascii=False, sort_keys=True) for candidate in candidates}
        if len(deltas) != len(candidates):
            errors.append(f"major gap {gap_id} patch candidates must contain materially distinct deltas")

    decision = document.get("decision_receipt")
    if not isinstance(decision, dict):
        errors.append("decision_receipt must be an object")
        decision = {}
    if not nonempty_string(decision.get("decision_id")):
        errors.append("decision_receipt requires decision_id")
    accepted = decision.get("accepted_patch_ids")
    if not isinstance(accepted, list) or not accepted:
        errors.append("decision_receipt requires at least one accepted patch")
        accepted = []
    for patch_id in accepted:
        if patch_id not in patch_ids:
            errors.append(f"decision_receipt accepts unknown patch {patch_id}")

    impact = document.get("patch_impact_receipt")
    if not isinstance(impact, dict):
        errors.append("patch_impact_receipt must be an object")
        impact = {}
    if impact.get("accepted_patch_id") not in accepted:
        errors.append("patch_impact_receipt.accepted_patch_id must resolve to the decision")
    for key in ("source_version_before", "source_version_after"):
        if not nonempty_string(impact.get(key)):
            errors.append(f"patch_impact_receipt requires {key}")
    for key in ("changed_truths", "invalidated_artifacts", "recompiled_stages", "regression_checks", "remaining_unknowns"):
        if not isinstance(impact.get(key), list):
            errors.append(f"patch_impact_receipt.{key} must be a list")

    regression = document.get("regression_receipt")
    if not isinstance(regression, dict):
        errors.append("regression_receipt must be an object")
        regression = {}
    for key in sorted(REGRESSION_KEYS):
        if key not in regression:
            errors.append(f"regression_receipt missing {key}")
    if regression.get("hard_locks_preserved") is not True:
        errors.append("regression_receipt.hard_locks_preserved must be true")
    if regression.get("new_contradictions") not in ([], None):
        errors.append("regression_receipt.new_contradictions must be empty before promotion")
    return errors, warnings


def load_document(path: Path) -> Any:
    return json.loads(path.read_text(encoding="utf-8"))


def main() -> int:
    if len(sys.argv) != 2:
        print("usage: validate_content_gap_repair.py repair.json", file=sys.stderr)
        return 2
    errors, warnings = validate(load_document(Path(sys.argv[1])))
    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())
