# Copyright 2026 Bakar Zhgenti
# SPDX-License-Identifier: Apache-2.0
"""Draft structural validator. Install jsonschema; run python validate.py example.json.
Pass --publish to reject drafts. Does not fetch sources or establish trust."""
import argparse, json
from pathlib import Path
from datetime import datetime
from jsonschema import Draft202012Validator, FormatChecker
p=argparse.ArgumentParser(); p.add_argument('profile'); p.add_argument('--publish',action='store_true'); a=p.parse_args()
schema=json.loads(Path(__file__).with_name('profile.schema.json').read_text())
data=json.loads(Path(a.profile).read_text())
errors=[e.message for e in Draft202012Validator(schema,format_checker=FormatChecker()).iter_errors(data)]
if not errors:
    def stamp(x): return datetime.fromisoformat(x.replace('Z','+00:00'))
    for group in ('offers','claims','sources'):
        ids=[x['id'] for x in data[group]]
        if len(ids)!=len(set(ids)): errors.append('Duplicate IDs: '+group)
    offers={x['id'] for x in data['offers']}; sources={x['id'] for x in data['sources']}
    if stamp(data['reviewed_at'])>stamp(data['updated_at']): errors.append('Review later than publication')
    for c in data['claims']:
        if c['subject'] not in offers|{'business'}: errors.append('Unknown subject: '+c['id'])
        if not set(c['source_ids'])<=sources: errors.append('Missing source: '+c['id'])
        if c['status']=='documented' and not c['source_ids']: errors.append('Documented claim lacks sources')
        if stamp(c['reviewed_at'])>stamp(data['updated_at']): errors.append('Claim review later than publication')
        if 'expires_at' in c and stamp(c['expires_at'])<stamp(c['reviewed_at']): errors.append('Claim expiry precedes review')
    if a.publish and data['publisher']['approval']!='owner_approved': errors.append('Owner approval required')
if errors:
    print('\n'.join(errors)); raise SystemExit(1)
print('Structural checks passed; factual accuracy, actual approval, ownership and source availability NOT verified.')
