﻿#!/usr/bin/env python3
"""Validate evidence boundaries for film-knowledge claim records."""

from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import Any


CLAIM_TYPES = {"HISTORICAL_FACT", "THEORY", "CRITICAL_INTERPRETATION", "CREATIVE_TRANSLATION"}
EVIDENCE_LEVELS = {"BODY_FULL", "BODY_SAMPLE", "BODY_LIMITED", "META_ONLY", "IMAGE_ONLY", "BROKEN_TIMEOUT", "BINARY_LIMITED"}
READABLE_LEVELS = {"BODY_FULL", "BODY_SAMPLE", "BODY_LIMITED"}


def validate(data: Any) -> tuple[list[str], list[str]]:
    errors: list[str] = []
    warnings: list[str] = []
    claims = data.get("claims") if isinstance(data, dict) else data
    if not isinstance(claims, list):
        return ["document must be a list or an object with a claims list"], warnings
    seen: set[str] = set()
    for index, claim in enumerate(claims):
        label = f"claim[{index}]"
        if not isinstance(claim, dict):
            errors.append(f"{label}: must be an object")
            continue
        claim_id = claim.get("claim_id")
        if not isinstance(claim_id, str) or not claim_id.strip():
            errors.append(f"{label}: missing claim_id")
        elif claim_id in seen:
            errors.append(f"{label}: duplicate claim_id {claim_id}")
        else:
            seen.add(claim_id)
        claim_type = claim.get("claim_type")
        evidence = claim.get("evidence_level")
        if claim_type not in CLAIM_TYPES:
            errors.append(f"{label}: unsupported claim_type")
        if evidence not in EVIDENCE_LEVELS:
            errors.append(f"{label}: unsupported evidence_level")
        if not isinstance(claim.get("claim"), str) or not claim["claim"].strip():
            errors.append(f"{label}: missing claim text")
        if not isinstance(claim.get("source_path_or_bibliography"), str) or not claim["source_path_or_bibliography"].strip():
            errors.append(f"{label}: missing source")
        if evidence in READABLE_LEVELS:
            if not isinstance(claim.get("locator"), str) or not claim["locator"].strip():
                errors.append(f"{label}: readable evidence requires a locator")
        else:
            if claim_type in CLAIM_TYPES and claim.get("content_conclusion", True):
                errors.append(f"{label}: unread/metadata evidence cannot support a content conclusion")
        authority = claim.get("authority", "REFERENCE_ONLY")
        if authority != "REFERENCE_ONLY":
            errors.append(f"{label}: knowledge claims must remain REFERENCE_ONLY")
        if claim_type == "CRITICAL_INTERPRETATION" and not claim.get("observable_work_evidence"):
            errors.append(f"{label}: criticism requires observable_work_evidence")
        if claim_type == "CREATIVE_TRANSLATION" and not claim.get("test_or_rejection_condition"):
            errors.append(f"{label}: creative translation requires a test or rejection condition")
        if claim.get("invokes_source_specific_method"):
            if claim.get("runtime_source_status") != "CURRENT_RUNTIME_PRESENT":
                errors.append(f"{label}: source-specific invocation requires CURRENT_RUNTIME_PRESENT")
            source_sha = claim.get("runtime_source_sha256")
            if not isinstance(source_sha, str) or len(source_sha) != 64 or any(char not in "0123456789abcdefABCDEF" for char in source_sha):
                errors.append(f"{label}: source-specific invocation requires a valid runtime_source_sha256")
            if not isinstance(claim.get("runtime_receipt_id"), str) or not claim["runtime_receipt_id"].strip():
                errors.append(f"{label}: source-specific invocation requires runtime_receipt_id")
        if claim_type == "HISTORICAL_FACT" and evidence == "BODY_LIMITED":
            warnings.append(f"{label}: historical fact has only limited body evidence")
    return errors, warnings


def main() -> int:
    if len(sys.argv) != 2:
        print("usage: validate_knowledge_claims.py claims.json", file=sys.stderr)
        return 2
    path = Path(sys.argv[1])
    data = json.loads(path.read_text(encoding="utf-8"))
    errors, warnings = validate(data)
    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())
