#!/usr/bin/env python3
"""Verify the fixed complete prefill JSON selection; recompute component observations only."""
import argparse
import copy
import hashlib
import json
from pathlib import Path, PurePosixPath
import tarfile
import tempfile

INDEX_SHA256 = '2c775c0cd25e3f6f7af221f2035fb21b6c202839c4a4421864e073f5ef1a98ac'
RUNS = ('44066488269', '44077343647')
SUPPORT = {'result.json', 'qual-stock-bi-joined.json', 'qual-stock-bi/outputs.json',
           'qual-stock-bi/runtime-identity.json', 'qual-stock-bi/worker-terminal.json',
           'qual-feature-cache/runtime-identity.json', 'qual-feature-cache.lifecycle.json',
           'qual-feature-cache.cleanup.json', 'configs/qual-feature-cache.json'}
SIGNATURE = ('original_tokens', 'prefix_tokens_computed', 'suffix_tokens',
             'prefix_padded_tokens', 'prefix_graph_mode')
COPY_SIGNATURE = ('canonical_sequence', 'prompt_sha256', 'start', 'stop', 'copied_bytes')


def require(condition, message):
    if not condition:
        raise ValueError(message)


def sha(path):
    digest = hashlib.sha256()
    with Path(path).open('rb') as source:
        for block in iter(lambda: source.read(1024*1024), b''):
            digest.update(block)
    return digest.hexdigest()


def read_records(archive_path, index_path):
    raw_index = Path(index_path).read_bytes()
    require(hashlib.sha256(raw_index).hexdigest() == INDEX_SHA256, 'Fixed membership index differs')
    index = json.loads(raw_index)
    require(index['schema'] == 'nodus.prefill-component-records/1'
            and index['derived_selection'] is True and index['scientific_execution'] is False
            and index['raw_tensors_included'] is False, 'Selection scope differs')
    descriptor = index['archive']
    require(Path(archive_path).stat().st_size == descriptor['bytes'] <= 32*1024**2
            and sha(archive_path) == descriptor['sha256'], 'Compressed companion bytes differ')
    require(len(index['members']) == descriptor['json_files'] == 186
            and descriptor['uncompressed_leaf_bytes'] == 79865906, 'Complete census differs')
    expected = {row['path']: row for row in index['members']}
    require(len(expected) == 186 and list(expected) == sorted(expected), 'Duplicate or unordered membership')
    records, seen, total = {}, set(), 0
    # Stream regular JSON leaves. Never extract paths, import original code or load tensors.
    with tarfile.open(archive_path, 'r|gz') as archive:
        for info in archive:
            path = PurePosixPath(info.name)
            require(info.isfile() and not path.is_absolute() and '..' not in path.parts
                    and info.name in expected and info.name not in seen, 'Unknown, duplicate or nonregular member')
            entry = expected[info.name]
            require(info.size == entry['bytes'] <= 4*1024**2, 'Leaf size differs')
            with archive.extractfile(info) as source:
                raw = source.read(info.size+1)
            require(len(raw) == info.size and hashlib.sha256(raw).hexdigest() == entry['sha256'], 'Leaf bytes differ')
            value = json.loads(raw)
            # Keep only the small fields needed for arithmetic; every original byte was checked above.
            if value.get('kind') == 'prefill_copy_readback':
                value = {key: value[key] for key in COPY_SIGNATURE + ('kind', 'ticket', 'observed_ns', 'readback_complete')}
            elif '/prefill-' in info.name and value.get('kind') != 'prefill_completed':
                value = {'kind': value.get('kind')}
            records[info.name] = value
            seen.add(info.name); total += info.size
    require(seen == set(expected) and total == descriptor['uncompressed_leaf_bytes'], 'Incomplete raw JSON selection')
    for run in RUNS:
        require(records[run+'/result.json']['records'][0]['outputs_sha256'] == expected[run+'/qual-stock-bi/outputs.json']['sha256'], 'Stock output byte binding differs')
    return records, index


def summarize(records):
    summaries, all_frames, all_copies = {}, {}, {}
    for run, prefill_count, frame_count, copy_count in zip(RUNS, (95, 73), (32, 24), (34, 26)):
        prefix = run+'/'
        own = {name[len(prefix):]: value for name, value in records.items() if name.startswith(prefix)}
        prefill = {name: value for name, value in own.items() if name.startswith('qual-feature-cache/prefill-')}
        require(len(prefill) == prefill_count and set(own)-set(prefill) == SUPPORT, 'Own-run census or support differs')
        result = own['result.json']; stock = result['records'][0]
        require(stock == own['qual-stock-bi-joined.json'] and len(own['qual-stock-bi/outputs.json']['outputs']) == 16, 'Stock joined record/output census differs')
        require(result['status'] == 'incomplete' and result['error_type'] == 'TimeoutError'
                and result['error'] == 'original work deadline' and result['performance_claim_eligible'] is False
                and len(result['records']) == 1, 'Incomplete experiment became a comparison result')
        require(stock['name'] == 'qual-stock-bi' and stock['complete_requests'] == stock['offered_requests'] == 16
                and stock['complete_bundles'] == stock['offered_bundles'] == 2 and stock['qualified_bundles'] == 1
                and stock['quality_pass'] is True and stock['latency_pass'] is False, 'Stock qualifier differs')
        require(abs(stock['full_job_seconds']-(stock['full_job_finished_ns']-stock['full_job_started_ns'])/1e9) < 1e-9,
                'Stock full-job clock differs')
        require(len(stock['scores']) == 16 and all(row['finished'] for row in stock['scores'].values()), 'Stock outputs incomplete')
        lifecycle = own['qual-feature-cache.lifecycle.json']
        require(lifecycle['command_error_type'] == 'TimeoutError'
                and lifecycle['owned_process']['reason'] == 'work_deadline'
                and lifecycle['owned_process']['qualification_passed'] is False
                and lifecycle['owned_process']['release_complete'] is False, 'Original failure flags differ')
        frames = sorted((v for v in prefill.values() if v.get('kind') == 'prefill_completed'), key=lambda v: v['started_ns'])
        copies = [v for v in prefill.values() if v.get('kind') == 'prefill_copy_readback']
        require(len(frames) == frame_count and len(copies) == copy_count, 'Completed/copy event count differs')
        require(len({v['ticket'] for v in frames}) == len(frames), 'Duplicate frame ticket')
        require(all(v['cuda_completion_proven'] is True and v['finished_ns'] >= v['started_ns'] for v in frames), 'Incomplete frame counted')
        require(all(v['readback_complete'] is True for v in copies), 'Incomplete copy readback')
        original = sum(v['original_tokens'] for v in frames)
        computed = sum(v['prefix_tokens_computed'] for v in frames)
        summaries[run] = {'complete_stock_outputs':16,'complete_stock_bundles':2,'qualified_stock_bundles':1,
            'stock_full_job_seconds':stock['full_job_seconds'],'stock_quality_pass':True,'stock_latency_pass':False,
            'prefill_json_files':prefill_count,'completed_custom_frames':len(frames),'copy_receipts':len(copies),
            'original_prefix_positions':original,'computed_prefix_positions':computed,
            'position_reduction_fraction':1-computed/original,'position_reduction_is_not_speedup':True,
            'custom_final_outputs_available':False,'custom_quality_verdict_available':False,
            'paired_performance_claim_eligible':False,'physical_gpu':lifecycle['device']['gpu_uuid']}
        all_frames[run], all_copies[run] = frames, copies
    old, new = (all_frames[run] for run in RUNS)
    matched = []
    for ordinal, (before, after) in enumerate(zip(old, new), 1):
        signature = {key:before[key] for key in SIGNATURE}
        require(signature == {key:after[key] for key in SIGNATURE}, 'Paired frame signature differs')
        paired_copies = []
        for run, frame in zip(RUNS, (before, after)):
            group = sorted((v for v in all_copies[run] if v['ticket'] == frame['ticket']), key=lambda v:v['observed_ns'])
            require(all(frame['started_ns'] <= v['observed_ns'] <= frame['finished_ns'] for v in group), 'Copy outside own frame')
            paired_copies.append(group)
        left, right = paired_copies
        require([{key:v[key] for key in COPY_SIGNATURE} for v in left]
                == [{key:v[key] for key in COPY_SIGNATURE} for v in right], 'Copy selection differs')
        if left:
            matched.append({'ordinal':ordinal,'old_ticket':before['ticket'],'new_ticket':after['ticket'],
                'copied_bytes':sum(v['copied_bytes'] for v in left),
                'old_interval_ns':max(v['observed_ns'] for v in left)-before['started_ns'],
                'new_interval_ns':max(v['observed_ns'] for v in right)-after['started_ns']})
    require(len(new) == 24 and len(matched) == 21, 'Matched subset differs')
    old_ns = sum(row['old_interval_ns'] for row in matched); new_ns = sum(row['new_interval_ns'] for row in matched)
    require((old_ns,new_ns,sum(row['copied_bytes'] for row in matched)) == (79475112028,149758174836,23235502080), 'Matched component arithmetic differs')
    require(summaries[RUNS[0]]['physical_gpu'] != summaries[RUNS[1]]['physical_gpu'], 'Different-physical-GPU scope differs')
    return {'runs':summaries,'matched_frames':matched,'matched_copy_intervals':21,'matched_copied_bytes':23235502080,
            'old_seconds':old_ns/1e9,'new_seconds':new_ns/1e9,'new_over_old_time':new_ns/old_ns,
            'scope':'Within-run host intervals from frame start through last copy/readback receipt; includes setup, copies, synchronization and verification. Cross-run, different physical A100s; not randomized causal or end-to-end speedup evidence.',
            'qualified_gain':False,'scientific_execution':False}


def self_test(records):
    cases = []
    wrong = copy.deepcopy(records); wrong.pop(next(p for p in wrong if '/prefill-' in p)); cases.append(wrong)
    wrong = copy.deepcopy(records); wrong[RUNS[0]+'/result.json']['performance_claim_eligible'] = True; cases.append(wrong)
    wrong = copy.deepcopy(records)
    next(v for p,v in wrong.items() if p.startswith(RUNS[1]+'/') and v.get('kind') == 'prefill_copy_readback')['copied_bytes'] += 1
    cases.append(wrong)
    for wrong in cases:
        try: summarize(wrong)
        except (ValueError,KeyError): continue
        raise AssertionError('Altered scientific boundary accepted')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('archive',type=Path); parser.add_argument('index',type=Path)
    parser.add_argument('--self-test',action='store_true');args=parser.parse_args()
    records,index = read_records(args.archive,args.index); result = summarize(records)
    if args.self_test:
        self_test(records)
        with tempfile.TemporaryDirectory() as temporary:
            wrong = Path(temporary)/'wrong'; wrong.write_bytes(b'corrupt')
            for archive,index_path in [(wrong,args.index),(args.archive,wrong)]:
                try: read_records(archive,index_path)
                except ValueError: continue
                raise AssertionError('Corrupt transport/index accepted')
        result['negative_controls'] = 5
    result.update(original_json_files=186,complete_prefill_json_files=168,original_json_bytes=index['archive']['uncompressed_leaf_bytes'])
    print(json.dumps(result,indent=2))
