#!/usr/bin/env python3
"""Offline structural validation for a pinned local JSON Schema set.
Usage: reference.py SCHEMA_DIRECTORY ROOT_SCHEMA REPORT_JSON
Does not establish source completeness or evaluation truth.
"""
import hashlib
import json
import sys
from pathlib import Path
from jsonschema import Draft202012Validator, FormatChecker
from referencing import Registry, Resource


def validate(directory, root_path, report_path):
    directory = Path(directory).resolve()
    root_path = Path(root_path).resolve()
    files = sorted(p.resolve() for p in directory.rglob('*.json')
                   if p.name != 'sha256.json')
    if not files or root_path not in files:
        raise ValueError('Root must belong to the local schema set')
    registry = Registry()  # No network retrieval callback.
    schemas, identifiers = {}, set()
    for path in files:
        schema = json.loads(path.read_text())
        uri = schema.get('$id')
        if not isinstance(uri, str) or not uri or uri in identifiers:
            raise ValueError('Missing or duplicate local schema identifier')
        Draft202012Validator.check_schema(schema)
        identifiers.add(uri)
        registry = registry.with_resource(uri, Resource.from_contents(schema))
        schemas[path] = schema
    report = json.loads(Path(report_path).read_text())
    formats = FormatChecker()
    if 'date-time' not in formats.checkers:
        raise ValueError('Install the pinned rfc3339-validator dependency')
    validator = Draft202012Validator(schemas[root_path], registry=registry,
                                     format_checker=formats)
    errors = [{'path': list(error.absolute_path), 'rule': error.validator}
              for error in validator.iter_errors(report)]
    return {
        'valid': not errors,
        'schema_sha256': hashlib.sha256(root_path.read_bytes()).hexdigest(),
        'errors': errors,
    }


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print('Usage: reference.py SCHEMA_DIRECTORY ROOT_SCHEMA REPORT_JSON',
              file=sys.stderr)
        sys.exit(2)
    try:
        result = validate(*sys.argv[1:])
    except Exception:
        # Parser/reference diagnostics can include report values; withhold them.
        print(json.dumps({'valid': False, 'error': 'Input, schema or reference failure'}))
        sys.exit(2)
    print(json.dumps(result))
    sys.exit(0 if result['valid'] else 1)
