#!/usr/bin/env python3
"""Offline GEO candidate contract validation. Does not fetch URLs or verify evidence bytes.

Requires Python >=3.9 and installed jsonschema. Run --help for usage.
"""
import argparse
import copy
import json
import sys
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit

try:
    from jsonschema import Draft202012Validator, FormatChecker
except ImportError:
    sys.exit('Missing dependency: jsonschema. No software was installed.')

ROOT = Path(__file__).resolve().parent
SCHEMA = ROOT / 'geo-delivery-1.0.0-rc.1.schema.json'
SURFACES = {'source_panel', 'inline', 'search_result', 'footnote'}
CHECKED = {'complete', 'partial', 'none_shown'}
EXTERNAL_LIMITS = [
    'No URL requests were made; actual accessibility and signed-link validity were not tested.',
    'No screenshot/raw-capture bytes were read; SHA-256 values, image dimensions and visual coverage were not verified.',
    'Privacy redaction, login state, model UI, IP geolocation and annotation truth require collection-side or human verification.',
    'An approval_reference is checked for presence, not for genuine customer approval.',
    'Passing --production is an offline gate, not proof that the delivery is authentic or externally accepted.'
]

def ptr(parts):
    return ''.join('/' + str(p).replace('~', '~0').replace('/', '~1') for p in parts)

def walk(value, path=()):
    yield path, value
    if isinstance(value, dict):
        for k, v in value.items():
            if k != 'unavailable_reasons':
                yield from walk(v, path + (k,))
    elif isinstance(value, list):
        for i, v in enumerate(value):
            yield from walk(v, path + (i,))

def moment(value):
    return None if value is None else datetime.fromisoformat(value.replace('Z', '+00:00'))

def contiguous(ranges, length):
    cursor = 0
    for r in sorted(ranges, key=lambda x: (x['start'], x['end'])):
        if r['start'] > cursor:
            return False
        cursor = max(cursor, r['end'])
    return cursor >= length

def validate(data, production=False, schema_path=SCHEMA):
    errors = []
    warnings = []
    def err(code, path, detail):
        errors.append({'code': code, 'path': path, 'message': detail})
    def require(condition, code, path, detail):
        if not condition:
            err(code, path, detail)
    schema = json.loads(Path(schema_path).read_text(encoding='utf-8'))
    Draft202012Validator.check_schema(schema)
    structural = sorted(Draft202012Validator(schema, format_checker=FormatChecker()).iter_errors(data),
                        key=lambda e: (ptr(e.absolute_path), e.message))
    for e in structural:
        err('schema', ptr(e.absolute_path), e.message)
    report = {'contract_version': '1.0.0-rc.1', 'mode': 'production' if production else 'review',
              'schema_valid': not structural, 'semantic_checks_run': not structural,
              'valid': False, 'errors': errors, 'warnings': warnings,
              'external_verification_performed': False, 'external_verification_limits': EXTERNAL_LIMITS}
    if structural:
        return report  # Do not run semantic rules on malformed structures.

    def unique(rows, key, path, code='duplicate_id'):
        seen = set()
        for i, row in enumerate(rows):
            val = row[key]
            require(val not in seen, code, f'{path}/{i}/{key}', f'Duplicate {key}: {val}')
            seen.add(val)
        return {r[key]: r for r in rows}

    def check_unavailable(scope, prefix, allow_missing_attempts=False):
        values = {ptr(p): v for p, v in walk(scope) if p}
        reasons = scope.get('unavailable_reasons', {})
        nulls = {p for p, v in values.items() if v is None}
        for p in nulls:
            require(p in reasons, 'null_reason_missing', prefix + p,
                    'Every null requires a nonempty reason in this entity\'s unavailable_reasons.')
        for p in reasons:
            exceptional = allow_missing_attempts and p == '/attempt_records' and scope['attempt_records'] == []
            require(p in nulls or exceptional, 'reason_pointer_invalid', prefix + '/unavailable_reasons',
                    f'{p} must point to a null observation, or the documented empty legacy attempt_records exception.')

    def slice_check(answer, record, key, path):
        start, end = record['start'], record['end']
        require(0 <= start < end <= len(answer), 'offset_range', path,
                'Offsets must form a nonempty half-open range within Unicode code points of answer_original.')
        require(answer[start:end] == record[key], 'quote_mismatch', path,
                f'answer_original[start:end] differs from {key}.')

    def time_order(a, b, path, code='time_order'):
        if a is not None and b is not None:
            require(moment(a) <= moment(b), code, path, f'{a} must not be after {b}.')

    delivery = data['delivery']; run = data['collection_run']
    brands = unique(data['brands'], 'brand_id', '/brands')
    prompts = unique(data['prompts'], 'prompt_id', '/prompts')
    plans = unique(run['sample_plan'], 'plan_id', '/collection_run/sample_plan')
    samples = unique(data['samples'], 'sample_id', '/samples')
    unique(data['failures'], 'failure_id', '/failures')
    profile = run['acceptance_profile']
    delivered_at = delivery['delivered_at_utc']
    policy = run['evidence_policy']
    check_unavailable(run, '/collection_run')
    if production:
        require(profile['confirmation_state'] == 'confirmed' and bool(profile.get('approval_reference')),
                'production_unconfirmed_profile', '/collection_run/acceptance_profile',
                'Production requires customer-confirmed rules with an approval reference.')
        require(policy['availability_until_utc'] is not None and policy['refresh_method'] is not None,
                'production_evidence_policy', '/collection_run/evidence_policy',
                'Production requires a stated evidence availability deadline and renewal method.')
    else:
        if profile['confirmation_state'] == 'proposed':
            warnings.append('Acceptance profile is proposed only, not customer-approved.')
    if policy['availability_until_utc']:
        time_order(delivered_at, policy['availability_until_utc'], '/collection_run/evidence_policy', 'evidence_policy_expired')

    for i, prompt in enumerate(data['prompts']):
        p = f'/prompts/{i}'
        for bid in prompt['monitored_brand_ids']:
            require(bid in brands, 'brand_reference', p + '/monitored_brand_ids', f'Unknown brand: {bid}')
        require(set(prompt['brands_in_prompt']) <= set(prompt['monitored_brand_ids']), 'prompt_brand_subset', p,
                'brands_in_prompt must be a subset of monitored_brand_ids; it does not express recommendation.')

    logical = set(); grid = defaultdict(list)
    for i, plan in enumerate(run['sample_plan']):
        p = f'/collection_run/sample_plan/{i}'
        key = (plan['prompt_id'], plan['platform'], plan['sample_index'])
        require(key not in logical, 'duplicate_plan_key', p, f'Duplicate logical sample slot: {key}')
        logical.add(key); grid[key[:2]].append(plan['sample_index'])
        require(plan['prompt_id'] in prompts, 'prompt_reference', p, 'Plan prompt does not exist.')
        if 'final_sample_id' in plan:
            require(plan['final_sample_id'] in samples, 'sample_reference', p, 'Final sample does not exist.')
            if plan['final_sample_id'] in samples:
                require(samples[plan['final_sample_id']]['plan_id'] == plan['plan_id'], 'final_sample_plan', p,
                        'Final sample belongs to a different plan; one sample cannot satisfy multiple slots.')
    for key, indices in grid.items():
        require(sorted(indices) == list(range(1, len(indices) + 1)), 'sample_index_sequence',
                '/collection_run/sample_plan', f'Sample indices must start at 1 and be contiguous within {key}.')
    if 'repeats_per_prompt' in delivery:
        r = delivery['repeats_per_prompt']
        platforms = {x['platform'] for x in plans.values()}
        counts = [len(grid.get((pid, platform), [])) for pid in prompts for platform in platforms]
        require(bool(counts) and all(n == r for n in counts), 'nonuniform_repeats', '/delivery/repeats_per_prompt',
                'Only fill repeats_per_prompt when every prompt/platform cell has the same planned count.')
    outcome_counts = Counter(p['outcome'] for p in plans.values())
    expected_counts = {'planned_sample_count': len(run['sample_plan']),
                       'delivered_sample_count': outcome_counts['accepted'],
                       'recorded_sample_count': len(data['samples']),
                       'failed_final_count': outcome_counts['failed'] + outcome_counts['excluded']}
    require(delivery['delivered_sample_count'] == sum(s['quality']['acceptance_status'] == 'accepted' for s in data['samples']),
            'accepted_sample_count', '/delivery/delivered_sample_count', 'Delivered count must also equal the number of accepted sample records.')
    for k, v in expected_counts.items():
        require(delivery[k] == v, 'delivery_count', '/delivery/' + k, f'Expected {v}, got {delivery[k]}.')
    require(delivery['planned_sample_count'] == delivery['delivered_sample_count'] + delivery['failed_final_count'],
            'delivery_balance', '/delivery', 'planned must equal delivered plus failed_final; retry attempts are not sample slots.')

    sample_plans = Counter(s['plan_id'] for s in data['samples'])
    for plan_id, n in sample_plans.items():
        require(n == 1, 'multiple_samples_per_plan', '/samples', f'{plan_id} has {n} retained final samples; at most one is allowed.')
    for i, sample in enumerate(data['samples']):
        p = f'/samples/{i}'; answer = sample['answer_original']; flags = set(sample['quality_flags'])
        check_unavailable(sample, p)
        plan = plans.get(sample['plan_id']); prompt = prompts.get(sample['prompt_id'])
        require(plan is not None, 'plan_reference', p + '/plan_id', 'Sample plan does not exist.')
        require(prompt is not None, 'prompt_reference', p + '/prompt_id', 'Sample prompt does not exist.')
        if plan:
            require(all(sample[k] == plan[k] for k in ['prompt_id', 'platform', 'sample_index']),
                    'plan_sample_key', p, 'Sample logical key must match its plan.')
            require(plan.get('final_sample_id') == sample['sample_id'], 'plan_sample_link', p,
                    'Every retained sample must be the final_sample_id of its plan.')
            require(plan['outcome'] == sample['quality']['acceptance_status'], 'plan_sample_status', p,
                    'Retained sample acceptance_status must match accepted/excluded plan outcome.')
        time_order(sample['submitted_at_utc'], sample['captured_at_utc'], p)
        time_order(sample['captured_at_utc'], delivered_at, p, 'capture_after_delivery')
        env = sample['environment']; geo = env['network_geography']
        time_order(geo['observed_at_utc'], delivered_at, p + '/environment/network_geography')
        if production:
            require(sample['origin'] != 'example' and 'demo_only' not in flags,
                    'production_demo', p, 'Synthetic/demo-only samples cannot pass production.')
        elif sample['origin'] == 'example' or 'demo_only' in flags:
            warnings.append(f'{sample["sample_id"]}: synthetic example; accepted is only a demonstration of proposed internal rules.')
        if sample['origin'] != 'legacy_import':
            require('legacy_source' not in sample, 'legacy_source_origin', p, 'legacy_source is reserved for legacy_import.')
        if prompt:
            modified = sample['prompt_submitted'] is not None and sample['prompt_submitted'] != prompt['original']
            require(('prompt_modified' in flags) == modified, 'prompt_modified_flag', p + '/quality_flags',
                    'prompt_modified must reflect an observed text difference; unknown historical text is not proof of modification.')
        if env['model_ui'] is None:
            require('model_unavailable' in flags, 'model_flag_missing', p, 'Null model_ui requires model_unavailable.')
        if env['search_enabled'] == 'unknown':
            require('search_state_unknown' in flags, 'search_flag_missing', p, 'Unknown search state requires a quality flag.')
        if sample['quality']['answer_status'] == 'partial':
            require('answer_truncated' in flags, 'answer_flag_missing', p, 'Partial answer requires answer_truncated.')
        if run['annotation']['reviewed_by'] == 'none':
            require('annotation_unreviewed' in flags, 'annotation_flag_missing', p, 'Unreviewed annotation requires a quality flag.')
        if 'answer_translated' in sample:
            require(run.get('translation', {}).get('method') in {'machine','human'}, 'translation_configuration', p,
                    'Translated answers require collection_run.translation with an actual method.')
            if run.get('translation', {}).get('method') == 'machine':
                require('translation_machine_only' in flags, 'translation_flag_missing', p, 'Machine translation must be flagged.')
            if run.get('translation', {}).get('source_language'):
                require(run['translation']['source_language'] == sample['answer_language'], 'translation_language', p,
                        'Batch translation source language conflicts with this answer.')
        results = unique(sample['brand_results'], 'brand_id', p + '/brand_results', 'duplicate_brand_result')
        if prompt:
            require(set(results) == set(prompt['monitored_brand_ids']), 'brand_result_coverage', p + '/brand_results',
                    'Each monitored brand must occur exactly once. Use not_evaluated rather than dropping a result.')
        citations = sample['citations']
        items = unique(citations['items'], 'citation_id', p + '/citations/items', 'duplicate_citation_id')
        all_occ = []; occ_ids = set(); seen_orders = set(); observed_counts = Counter(); source_urls = set()
        for ci, item in enumerate(citations['items']):
            cp = f'{p}/citations/items/{ci}'
            if item['url'] is not None:
                require(item['url'] not in source_urls, 'duplicate_source_url', cp,
                        'An identical original URL is represented once; put its repeated appearances in occurrences. No URL normalization is applied.')
                source_urls.add(item['url'])
            if 'owner_brand_id' in item:
                require(item['owner_brand_id'] in brands, 'owner_brand_reference', cp, 'Unknown source owner brand.')
                owner = brands.get(item['owner_brand_id'], {})
                domains = owner.get('official_domains', [])
                hosts = [urlsplit(u).hostname for u in [item.get('url'), item.get('final_url')] if u]
                require(any(h and (h == d or h.endswith('.'+d)) for h in hosts for d in domains),
                        'owner_domain_evidence', cp, 'owner_brand_id requires a URL host matching the brand\'s official_domains.')
            if item['source_type'] == 'official_brand':
                require('owner_brand_id' in item, 'official_owner_missing', cp, 'official_brand requires an owner_brand_id.')
            for oi, occ in enumerate(item['occurrences']):
                op = f'{cp}/occurrences/{oi}'; oid = occ['occurrence_id']; sf = occ['surface']
                require(oid not in occ_ids, 'duplicate_occurrence_id', op, f'Duplicate occurrence ID: {oid}')
                occ_ids.add(oid); all_occ.append(occ); observed_counts[sf] += 1
                order = occ.get('display_order')
                if order is not None:
                    require((sf, order) not in seen_orders, 'duplicate_display_order', op,
                            'Non-null display_order must be unique within its surface.')
                    seen_orders.add((sf, order))
                if sf == 'unknown':
                    require('citation_origin_unknown' in flags, 'citation_origin_flag', op,
                            'Unknown citation surface requires citation_origin_unknown.')
                for li, link in enumerate(occ['answer_links']):
                    slice_check(answer, link, 'quote', f'{op}/answer_links/{li}')
        surface_rows = unique(citations['surfaces'], 'surface', p + '/citations/surfaces', 'duplicate_surface')
        require(set(surface_rows) == SURFACES, 'surface_coverage', p + '/citations/surfaces', 'All four surfaces must occur exactly once.')
        expected_checked = {sf for sf, row in surface_rows.items() if row['status'] in CHECKED}
        require(set(citations['checked_surfaces']) == expected_checked, 'checked_surfaces', p + '/citations/checked_surfaces',
                'checked_surfaces must equal actually inspected surfaces, excluding not_checked and unavailable.')
        for si, sf in enumerate(citations['surfaces']):
            sp = f'{p}/citations/surfaces/{si}'; actual = observed_counts[sf['surface']]
            require(sf['captured_count'] == actual, 'surface_count', sp, f'captured_count must equal occurrence count {actual}, not distinct-source count.')
            total = sf.get('displayed_total')
            if total is not None:
                require(total >= actual, 'surface_total', sp, 'displayed_total cannot be less than captured occurrences.')
                if sf['status'] in {'complete', 'none_shown'}:
                    require(total == actual, 'surface_complete_count', sp, 'Complete/none_shown total must equal captured occurrences.')
            if sf['status'] in {'none_shown', 'not_checked', 'unavailable'}:
                require(actual == 0, 'surface_status_conflict', sp, 'This surface status cannot contain occurrences.')
            if sf['status'] == 'complete' and sf['surface'] in {'source_panel','search_result','footnote'}:
                require(all(o.get('display_order') is not None for o in all_occ if o['surface'] == sf['surface']),
                        'complete_display_order', sp, 'Complete list surfaces require known display orders.')
                orders = [o.get('display_order') for o in all_occ if o['surface'] == sf['surface']]
                require(all(x is not None for x in orders) and sorted(x for x in orders if x is not None) == list(range(1, len(orders)+1)),
                        'complete_display_sequence', sp, 'Complete list display orders must be contiguous from 1.')
        states = [x['status'] for x in surface_rows.values()]
        if citations['status'] == 'complete':
            require(all(item['url'] is not None for item in citations['items']), 'complete_citation_url_missing', p + '/citations',
                    'A visible source without its captured original URL is an incomplete source record; use partial and explain the gap.')
            require(bool(items) and len(states) == 4 and all(s in {'complete','none_shown'} for s in states)
                    and observed_counts['unknown'] == 0, 'citation_complete_conflict', p + '/citations',
                    'Complete requires all four surfaces resolved and no unknown occurrence surface. Use none_shown for zero sources.')
        elif citations['status'] == 'none_shown':
            require(not items and len(states) == 4 and all(s == 'none_shown' for s in states), 'citation_none_conflict', p + '/citations',
                    'none_shown requires all four surfaces checked and showing no sources.')
        elif citations['status'] == 'not_checked':
            require(not expected_checked and not items, 'citation_unchecked_conflict', p + '/citations',
                    'not_checked cannot claim inspected surfaces or captured sources.')
        else:
            require('citation_list_not_confirmed_complete' in flags, 'citation_partial_flag', p,
                    'Partial citations require citation_list_not_confirmed_complete.')
        if citations['status'] == 'not_checked':
            require('citation_list_not_confirmed_complete' in flags, 'citation_partial_flag', p,
                    'Unchecked citations require citation_list_not_confirmed_complete.')

        for bi, result in enumerate(sample['brand_results']):
            bp = f'{p}/brand_results/{bi}'
            require(result['brand_id'] in brands, 'brand_reference', bp, 'Unknown brand in result.')
            if result['mention_status'] == 'not_mentioned':
                require(sample['quality']['answer_status'] == 'complete', 'not_mentioned_incomplete', bp,
                        'Incomplete/unknown answers cannot establish not_mentioned; use not_evaluated or uncertain with a reason.')
            for mi, m in enumerate(result['mentions']):
                mp = f'{bp}/mentions/{mi}'; slice_check(answer, m, 'evidence_quote', mp)
                ns, ne = m['name_start'], m['name_end']
                require(m['start'] <= ns < ne <= m['end'], 'name_range', mp,
                        'The exact brand-name range must be inside the evidence quote range.')
                require(answer[ns:ne] == m['name_in_answer'], 'name_mismatch', mp,
                        'answer_original[name_start:name_end] differs from name_in_answer.')
                for cid in m['citation_ids']:
                    require(cid in items, 'citation_reference', mp, f'Unknown sample-local citation ID: {cid}')
        for ei, entity in enumerate(sample['other_entities_mentioned']):
            ep = f'{p}/other_entities_mentioned/{ei}'; slice_check(answer, entity, 'evidence_quote', ep)
            require(entity['name'] in entity['evidence_quote'], 'entity_name_mismatch', ep,
                    'Entity name must occur in the quoted original text; no competitor classification is inferred.')

        evidence = sample['evidence']; shots = evidence['screenshots']
        seq = [x['sequence'] for x in shots]
        require(seq == list(range(1, len(shots) + 1)), 'screenshot_sequence', p + '/evidence/screenshots',
                'Screenshot sequence must be unique, contiguous, start at 1 and follow array order.')
        ranges = []; covered_occ = set()
        for si, shot in enumerate(shots):
            sp = f'{p}/evidence/screenshots/{si}'
            ranges.extend(shot['answer_ranges']); covered_occ.update(shot['citation_occurrence_ids'])
            for r in shot['answer_ranges']:
                require(0 <= r['start'] < r['end'] <= len(answer), 'screenshot_range', sp,
                        'Screenshot answer range must lie within original answer code points.')
            require(set(shot['citation_occurrence_ids']) <= occ_ids, 'screenshot_citation_reference', sp,
                    'Screenshot citation_occurrence_ids must refer to this sample\'s occurrence IDs.')
            time_order(shot['captured_at_utc'], delivered_at, sp, 'capture_after_delivery')
            time_order(shot['access_checked_at_utc'], delivered_at, sp, 'access_check_after_delivery')
            time_order(shot['captured_at_utc'], shot['access_checked_at_utc'], sp)
        full_answer = bool(shots) and contiguous(ranges, len(answer))
        full_citations = bool(occ_ids) and covered_occ == occ_ids
        if evidence['answer_coverage'] == 'complete':
            require(full_answer, 'answer_coverage_gap', p + '/evidence', 'Complete screenshot answer coverage must cover [0, len(answer_original)) without a gap.')
        elif evidence['answer_coverage'] == 'partial':
            require(bool(ranges) and not full_answer, 'answer_partial_conflict', p + '/evidence', 'Partial answer coverage requires some coverage and at least one gap.')
        else:
            require(not ranges, 'answer_unchecked_conflict', p + '/evidence', 'Unchecked answer coverage must not declare verified ranges.')
        ccoverage = evidence['citations_coverage']
        if ccoverage == 'complete':
            require(full_citations and citations['status'] == 'complete', 'citation_coverage_gap', p + '/evidence',
                    'Complete screenshot citation coverage requires complete citations and every occurrence covered.')
        elif ccoverage == 'none_shown':
            require(citations['status'] == 'none_shown' and not covered_occ, 'citation_coverage_none', p + '/evidence',
                    'none_shown screenshot state requires citations.none_shown.')
        elif ccoverage == 'partial':
            require(not (full_citations and citations['status'] == 'complete'), 'citation_partial_conflict', p + '/evidence',
                    'Partial coverage cannot claim complete coverage of a complete citation set.')
        else:
            require(not covered_occ, 'citation_unchecked_conflict', p + '/evidence', 'Unchecked screenshot citation coverage must not declare verified IDs.')
        evidence_links = [(f'{p}/evidence/screenshots/{si}', x) for si, x in enumerate(shots)]
        if 'raw_capture' in evidence:
            evidence_links.append((p + '/evidence/raw_capture', evidence['raw_capture']))
        for lp, resource in evidence_links:
            if resource['access_mode'] == 'signed_url':
                time_order(delivered_at, resource['expires_at_utc'], lp, 'signed_url_expired')
                if production and policy['availability_until_utc']:
                    time_order(policy['availability_until_utc'], resource['expires_at_utc'], lp, 'signed_url_policy_gap')

        if sample['quality']['acceptance_status'] == 'accepted':
            checks = {
                'require_logged_in': env['account_state'] == 'logged_in',
                'require_original_prompt': prompt is not None and sample['prompt_submitted'] == prompt['original'],
                'require_complete_answer': sample['quality']['answer_status'] == 'complete',
                'require_complete_citations': citations['status'] in {'complete', 'none_shown'},
                'require_complete_screenshots': evidence['answer_coverage'] == 'complete' and evidence['citations_coverage'] in {'complete', 'none_shown'},
                'require_verified_geography': all(geo.get(k) is not None for k in ['country','source','observed_at_utc']),
                'require_all_brand_evaluations': all(x['mention_status'] in {'mentioned','not_mentioned'} for x in results.values())
            }
            for key, condition in checks.items():
                if profile[key]:
                    require(condition, 'acceptance_profile', p, f'Accepted sample violates {key}.')
            if production:
                require(sample['submitted_at_utc'] is not None and sample['captured_at_utc'] is not None,
                        'production_sample_times', p, 'Production accepted samples require observed submission and capture times.')
                require(evidence['redaction_status'] == 'verified' and evidence['access_status'] == 'accessible',
                        'production_evidence_attestation', p + '/evidence',
                        'Production accepted samples require collection-side/human access and redaction attestations; offline code does not verify truth.')
                require(bool(shots), 'production_screenshots_missing', p + '/evidence', 'Production accepted samples require screenshots.')
                for si, shot in enumerate(shots):
                    require(all(shot[k] is not None for k in ['sha256','width','height','captured_at_utc','access_checked_at_utc']),
                            'production_screenshot_metadata', f'{p}/evidence/screenshots/{si}',
                            'Accepted production screenshots require hash, dimensions, capture time and access-check time.')
                if 'raw_capture' in evidence:
                    require(evidence['raw_capture']['sha256'] is not None, 'production_raw_hash', p + '/evidence/raw_capture',
                            'Provided production raw capture requires a hash value; byte correctness is checked externally.')
                for ci, item in enumerate(citations['items']):
                    require(item['url'] is not None, 'production_citation_url', f'{p}/citations/items/{ci}',
                            'Production accepted sources require the captured original URL.')

    failure_plans = set(); attempt_ids = set()
    for i, failure in enumerate(data['failures']):
        p = f'/failures/{i}'; pid = failure['plan_id']; plan = plans.get(pid)
        require(pid not in failure_plans, 'duplicate_failure_plan', p, 'At most one failure/retry summary is allowed per logical plan.')
        failure_plans.add(pid)
        require(plan is not None, 'plan_reference', p, 'Failure plan does not exist.')
        require(failure['prompt_id'] in prompts, 'prompt_reference', p, 'Failure prompt does not exist.')
        check_unavailable(failure, p, allow_missing_attempts=True)
        if plan:
            require(all(failure[k] == plan[k] for k in ['prompt_id','platform','sample_index']), 'failure_plan_key', p,
                    'Failure logical key must match plan.')
            expected = 'accepted' if failure['final_status'] == 'recovered' else failure['final_status']
            require(plan['outcome'] == expected, 'failure_plan_status', p, 'Failure final_status conflicts with plan outcome.')
        records = failure['attempt_records']
        legacy_empty = not records and '/attempt_records' in failure.get('unavailable_reasons', {})
        if legacy_empty:
            warnings.append(f'{failure["failure_id"]}: historical per-attempt records unavailable; attempts cannot be independently reconciled.')
            require(not production, 'production_missing_attempts', p, 'Historical missing per-attempt records cannot pass production.')
        else:
            require(bool(records), 'attempt_records_missing', p, 'No attempt records: provide records or an explicit historical unavailability reason.')
            require(failure['attempts'] == len(records), 'attempt_count', p, 'attempts must equal attempt_records length.')
        for ai, record in enumerate(records):
            ap = f'{p}/attempt_records/{ai}'
            require(record['attempt_index'] == ai + 1, 'attempt_sequence', ap, 'Attempt indices must start at 1 and be continuous in array order.')
            require(record['attempt_id'] not in attempt_ids, 'duplicate_attempt_id', ap, 'Attempt ID must be unique across the delivery.')
            attempt_ids.add(record['attempt_id'])
            time_order(record['started_at_utc'], record['ended_at_utc'], ap)
            time_order(record['ended_at_utc'], delivered_at, ap, 'attempt_after_delivery')
            if ai:
                time_order(records[ai-1]['ended_at_utc'], record['started_at_utc'], ap)
            if ai < len(records)-1:
                require(record['status'] != 'succeeded', 'attempt_after_success', ap, 'No later attempt may follow a succeeded terminal attempt in the same plan.')
            if production:
                require(record['started_at_utc'] is not None and record['ended_at_utc'] is not None,
                        'production_attempt_times', ap, 'Production requires per-attempt start/end times.')
        time_order(failure['last_attempt_at_utc'], delivered_at, p, 'attempt_after_delivery')
        if production:
            require(failure['last_attempt_at_utc'] is not None, 'production_attempt_times', p, 'Production requires last_attempt_at_utc.')
        if records:
            expected_status = {'recovered':'succeeded','failed':'failed','excluded':'excluded'}[failure['final_status']]
            require(records[-1]['status'] == expected_status, 'attempt_terminal_status', p, 'Last attempt status must match failure summary.')
            require(failure['last_attempt_at_utc'] == records[-1]['ended_at_utc'], 'last_attempt_time', p,
                    'last_attempt_at_utc must equal the terminal attempt end time, including null when historically unknown.')
        if failure['final_status'] == 'recovered':
            sid = failure['recovered_sample_id']; sample = samples.get(sid)
            require(sample is not None, 'recovered_sample_reference', p, 'Recovered sample does not exist.')
            if sample:
                require(sample['plan_id'] == pid and sample['quality']['acceptance_status'] == 'accepted', 'recovered_sample_plan', p,
                        'Recovered sample must be accepted and belong to the same plan.')
            if plan:
                require(plan.get('final_sample_id') == sid, 'recovered_final_sample', p, 'Recovered sample must be the final sample in the plan.')
            if records:
                require(len(records) >= 2 and any(x['status'] in {'failed','excluded'} for x in records[:-1]),
                        'unnecessary_failure_summary', p, 'Initial success does not require a recovery summary; recovery requires an earlier failed/excluded attempt.')
        if plan and plan.get('final_sample_id') in samples:
            sample = samples[plan['final_sample_id']]
            if records:
                require(sample['attempt_index'] == records[-1]['attempt_index'], 'sample_attempt_link', p,
                        'Final sample attempt_index must match terminal attempt.')
                time_order(records[-1]['started_at_utc'], sample['submitted_at_utc'], p)
                time_order(sample['captured_at_utc'], records[-1]['ended_at_utc'], p)
            elif legacy_empty:
                require(sample['attempt_index'] == failure['attempts'], 'sample_attempt_link', p,
                        'Historical final sample attempt_index must match declared attempt count.')
    for i, plan in enumerate(run['sample_plan']):
        p = f'/collection_run/sample_plan/{i}'
        if plan['outcome'] in {'failed','excluded'}:
            require(plan['plan_id'] in failure_plans, 'missing_failure_summary', p, 'A failed/excluded final plan requires a failure summary.')
        if plan['outcome'] == 'accepted':
            sample = samples.get(plan.get('final_sample_id'))
            if sample:
                if sample['attempt_index'] > 1:
                    require(plan['plan_id'] in failure_plans, 'missing_retry_history', p, 'Retried accepted sample requires a recovery history.')
                else:
                    require(plan['plan_id'] not in failure_plans, 'initial_success_summary', p, 'A first-attempt success does not belong in failures.')
    report['valid'] = not errors
    return report


def self_test(schema_path=SCHEMA):
    baseline = json.loads((ROOT/'example-delivery.json').read_text(encoding='utf-8'))
    cases = []
    def run_case(name, data, expected_valid, code=None, production=False):
        result = validate(data, production=production, schema_path=schema_path)
        codes = {e['code'] for e in result['errors']}
        passed = result['valid'] == expected_valid and (code is None or code in codes)
        cases.append({'name':name, 'mode':'production' if production else 'review', 'expected_valid':expected_valid,
                      'actual_valid':result['valid'], 'expected_error_code':code, 'observed_error_codes':sorted(codes),
                      'passed':passed, 'errors':result['errors']})
    run_case('synthetic_positive_review', baseline, True)
    run_case('synthetic_rejected_in_production', baseline, False, 'production_demo', True)
    def broken(name, fn, code, production=False):
        d = copy.deepcopy(baseline); fn(d); run_case(name,d,False,code,production)
    broken('unknown_field', lambda d:d['delivery'].update({'surprise':True}), 'schema')
    broken('wrong_schema_version', lambda d:d.update({'schema_version':'1.0.0'}), 'schema')
    broken('wrong_delivery_count', lambda d:d['delivery'].update({'recorded_sample_count':9}), 'delivery_count')
    broken('duplicate_brand_id', lambda d:d['brands'].append(copy.deepcopy(d['brands'][0])), 'duplicate_id')
    broken('unknown_prompt_reference', lambda d:d['samples'][0].update({'prompt_id':'absent'}), 'prompt_reference')
    broken('duplicate_plan_key', lambda d:d['collection_run']['sample_plan'][1].update({'sample_index':1}), 'duplicate_plan_key')
    broken('incorrect_final_sample', lambda d:d['collection_run']['sample_plan'][0].update({'final_sample_id':'absent'}), 'sample_reference')
    broken('brand_result_missing', lambda d:d['samples'][0]['brand_results'].pop(), 'brand_result_coverage')
    broken('duplicate_brand_result', lambda d:d['samples'][0]['brand_results'].append(copy.deepcopy(d['samples'][0]['brand_results'][0])), 'duplicate_brand_result')
    broken('quote_offset_utf16_error', lambda d:d['samples'][0]['brand_results'][0]['mentions'][0].update({'start':8}), 'quote_mismatch')
    broken('incorrect_name_offset', lambda d:d['samples'][0]['brand_results'][0]['mentions'][0].update({'name_start':0}), 'name_range')
    broken('dangling_citation_id', lambda d:d['samples'][0]['brand_results'][0]['mentions'][0].update({'citation_ids':['absent']}), 'citation_reference')
    def incomplete_url(d):
        d['samples'][0]['citations']['items'][0]['url']=None
        d['samples'][0]['unavailable_reasons']['/citations/items/0/url']='The platform did not expose a recoverable original URL.'
    broken('complete_citations_with_missing_url',incomplete_url,'complete_citation_url_missing')
    broken('surface_count_mismatch', lambda d:d['samples'][0]['citations']['surfaces'][0].update({'captured_count':2}), 'surface_count')
    broken('duplicate_occurrence_id', lambda d:d['samples'][0]['citations']['items'][0]['occurrences'][1].update({'occurrence_id':'occ_inline'}), 'duplicate_occurrence_id')
    def duplicate_order(d):
        c=d['samples'][0]['citations']; extra=copy.deepcopy(c['items'][0]['occurrences'][1]); extra['occurrence_id']='occ_panel_2'; c['items'][0]['occurrences'].append(extra)
    broken('duplicate_surface_display_order', duplicate_order, 'duplicate_display_order')
    broken('checked_surface_mismatch', lambda d:d['samples'][0]['citations'].update({'checked_surfaces':['inline']}), 'checked_surfaces')
    broken('screenshot_sequence_gap', lambda d:d['samples'][0]['evidence']['screenshots'][0].update({'sequence':2}), 'screenshot_sequence')
    broken('screenshot_answer_gap', lambda d:d['samples'][0]['evidence']['screenshots'][0]['answer_ranges'][0].update({'start':1}), 'answer_coverage_gap')
    broken('screenshot_citation_gap', lambda d:d['samples'][0]['evidence']['screenshots'][0].update({'citation_occurrence_ids':['occ_inline']}), 'citation_coverage_gap')
    broken('missing_null_reason', lambda d:d['samples'][0]['unavailable_reasons'].pop('/environment/model_ui'), 'null_reason_missing')
    broken('dangling_reason_pointer', lambda d:d['samples'][0]['unavailable_reasons'].update({'/does_not_exist':'test'}), 'reason_pointer_invalid')
    broken('non_utc_time', lambda d:d['delivery'].update({'delivered_at_utc':'2026-11-11T09:00:00+00:00'}), 'schema')
    def expired(d): d['samples'][0]['evidence']['screenshots'][0].update({'access_mode':'signed_url','expires_at_utc':'2026-11-11T08:00:00Z'})
    broken('signed_url_expired',expired,'signed_url_expired')
    broken('incorrect_attempt_count',lambda d:d['failures'][0].update({'attempts':3}),'attempt_count')
    broken('attempt_sequence_gap',lambda d:d['failures'][0]['attempt_records'][1].update({'attempt_index':3}),'attempt_sequence')
    broken('wrong_terminal_attempt',lambda d:d['failures'][0]['attempt_records'][1].update({'status':'failed','reason_code':'other'}),'attempt_terminal_status')
    broken('wrong_recovered_sample',lambda d:d['failures'][0].update({'recovered_sample_id':'absent'}),'recovered_sample_reference')
    broken('profile_requires_login',lambda d:d['samples'][0]['environment'].update({'account_state':'logged_out'}),'acceptance_profile')
    broken('production_unconfirmed',lambda d:None,'production_unconfirmed_profile',True)
    def unknown_brand(d): d['samples'][0]['brand_results'][1].update({'mention_status':'not_evaluated','reason':'not reviewed'})
    broken('unreviewed_brand_cannot_be_accepted',unknown_brand,'acceptance_profile')
    def partial_answer(d): d['samples'][0]['quality']['answer_status']='partial'; d['samples'][0]['quality_flags'].append('answer_truncated')
    broken('negative_claim_on_partial_answer',partial_answer,'not_mentioned_incomplete')
    broken('raw_pii_prohibited',lambda d:d['samples'][0]['evidence'].update({'raw_capture':{'kind':'html','url':'https://example.com/raw','sha256':None,'contains_pii':True,'access_mode':'public'}}),'schema')
    broken('nonuniform_repeats',lambda d:d['delivery'].update({'repeats_per_prompt':3}),'nonuniform_repeats')
    def signed_policy_gap(d):
        d['collection_run']['evidence_policy']={'availability_until_utc':'2026-12-01T09:00:00Z','refresh_method':'Renew URLs and revalidate before delivery.'}
        d['collection_run'].pop('unavailable_reasons')
        d['samples'][0]['evidence']['screenshots'][0].update({'access_mode':'signed_url','expires_at_utc':'2026-11-12T09:00:00Z'})
    broken('production_signed_availability_gap',signed_policy_gap,'signed_url_policy_gap',True)
    def missing_legacy_attempts(d):
        f=d['failures'][0]; f['attempt_records']=[]; f['unavailable_reasons']={'/attempt_records':'Legacy source did not retain per-attempt records.'}
    archival=copy.deepcopy(baseline); missing_legacy_attempts(archival)
    run_case('legacy_attempt_gap_retained_for_review',archival,True)
    run_case('legacy_attempt_gap_blocked_in_production',archival,False,'production_missing_attempts',True)
    def unknown_submission(d):
        sm=d['samples'][0]; sm['prompt_submitted']=None; sm['unavailable_reasons']['/prompt_submitted']='Legacy source did not preserve the submitted text.'
    broken('unknown_submitted_text_not_accepted',unknown_submission,'acceptance_profile')
    # Positive retained-excluded sample: planned outcome is excluded, not a second delivered sample.
    excluded=copy.deepcopy(baseline); s=excluded['samples'][0]
    s['quality']={'answer_status':'complete','acceptance_status':'excluded','exclusion_reasons':['Synthetic exclusion scenario.']}
    excluded['collection_run']['sample_plan'][0]['outcome']='excluded'
    excluded['delivery'].update({'delivered_sample_count':0,'failed_final_count':2})
    f=excluded['failures'][0]; f['final_status']='excluded'; f.pop('recovered_sample_id'); f['attempt_records'][-1].update({'status':'excluded','reason_code':'other'})
    unknown_submission(excluded)
    run_case('retained_excluded_sample_positive_review',excluded,True)
    # Fresh initial success has no recovery summary and remains one logical sample.
    first=copy.deepcopy(baseline); first['samples'][0]['attempt_index']=1; first['failures'].pop(0)
    run_case('first_attempt_success_positive_review',first,True)
    return {'contract_version':'1.0.0-rc.1','generated_at_utc':datetime.now(timezone.utc).isoformat().replace('+00:00','Z'),
            'suite':'offline structural and semantic regression tests', 'passed':all(c['passed'] for c in cases),
            'total':len(cases),'passed_count':sum(c['passed'] for c in cases),'negative_fixture_count':sum(not c['expected_valid'] for c in cases),
            'external_verification_performed':False,'external_verification_limits':EXTERNAL_LIMITS,'tests':cases}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('input', nargs='?', type=Path, help='Delivery JSON to validate')
    parser.add_argument('--schema',type=Path,default=SCHEMA)
    parser.add_argument('--production',action='store_true',help='Apply additional production metadata and approval gates; does not verify external facts')
    parser.add_argument('--self-test',action='store_true',help='Run in-memory positive and deliberately broken fixtures')
    parser.add_argument('--report',type=Path,help='Write a machine-readable JSON report')
    args=parser.parse_args()
    if args.self_test:
        result=self_test(args.schema); success=result['passed']
    else:
        if args.input is None: parser.error('Specify an input JSON or --self-test.')
        try: data=json.loads(args.input.read_text(encoding='utf-8'))
        except (OSError,UnicodeError,json.JSONDecodeError) as e:
            result={'valid':False,'schema_valid':False,'semantic_checks_run':False,'errors':[{'code':'input_read','path':'','message':str(e)}]}
        else: result=validate(data,args.production,args.schema)
        success=result['valid']
    rendered=json.dumps(result,ensure_ascii=False,indent=2)+'\n'
    if args.report: args.report.write_text(rendered,encoding='utf-8')
    print(rendered,end='')
    return 0 if success else 1

if __name__=='__main__':
    raise SystemExit(main())
