#!/usr/bin/env python3
"""Replay the fixed public Triton comparison with its original stdlib reducers."""
import argparse
import copy
import csv
import hashlib
import io
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import zipfile

ZIP_SHA = 'e454c54fde3ff0ae569c6e0bde141a1d21a0883fd5574db7eed9951bc8315241'
CLOCK_SHA = '69248950ea028b51559d2d7f724728fddd90fb88ab4fd5fc19da2d766b8db626'
POLICIES = ('nodus-causal-whole', 'triton-fifo-graph32',
            'triton-priority-dynamic', 'triton-priority-graph32')
ARMS = ('local-graph-solo', 'triton-graph-solo', 'triton-fifo-graph32',
        'triton-priority-graph32', 'triton-dynamic-solo',
        'triton-priority-dynamic', 'causal-whole32',
        'unconditional-layer32', 'causal-layer32')


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


def validate(clocks, observed):
    require(clocks['source_run'] == 44537351420, 'original experiment')
    require(set(clocks['schedules']) == {'smooth', 'burst'}, 'both schedules')
    require(len(observed['windows']) == 18, 'all 18 dispositions')
    expected = [(f's{s}a{a}', schedule, arm)
                for s, schedule in enumerate(('smooth', 'burst'))
                for a, arm in enumerate(ARMS)]
    require([(r['window'], r['schedule'], r['arm']) for r in observed['windows']]
            == expected, 'unique ordered windows')
    for schedule, policies in clocks['schedules'].items():
        require(set(policies) == set(POLICIES), 'all matched stock policies')
        width, step = (1, 500_000_000) if schedule == 'smooth' else (6, 3_000_000_000)
        offers = sorted(t for t in range(0, 300_000_000_000, step) for _ in range(width))
        for cell in policies.values():
            require(cell['duration_ns'] == 300_000_000_000, 'five-minute clock')
            require(sorted(t for t, _ in cell['foreground']) == offers,
                    'all 600 original offered requests')
            require(all(type(t) is int and type(end) is int and 0 <= t < end
                        for t, end in cell['foreground']), 'live clock ordering')
            for batch in cell['batches']:
                require(0 <= batch['start'] < batch['drain'], 'physical clock ordering')
                require(len(batch['returns']) == batch['background'] and
                        all(t >= batch['drain'] for t in batch['returns']),
                        'correct background return census')
    for row in observed['windows']:
        require(row['formal_arm_eligible'] is False, 'original formal eligibility')
        if row['arm'] in ARMS[-2:]:
            require(row['original_scoring'] == 'refused' and row['formal_arm_status'] == 'failed'
                    and 'timely_periods' not in row, 'failed layer windows remain unscored')
            continue
        require(row['original_scoring'] == 'verified', 'independent score disposition')
        if row['arm'] == 'causal-whole32':
            require(row['formal_arm_status'] == 'failed' and
                    row['formal_causal_refusal'] == 'ValueError:causal original window differs',
                    'original clock refusal remains')
        require(len(row['timely_periods']) == len(row['background_returns_in_each_period'])
                == row['periods'], 'every period retained')
        require(sum(row['background_returns_in_each_period']) == row['background_returns'],
                'background count equals period sum')
        key = 'nodus-causal-whole' if row['arm'] == 'causal-whole32' else row['arm']
        if key in POLICIES:
            batches = clocks['schedules'][row['schedule']][key]['batches']
            require(sum(len(b['returns']) for b in batches) == row['background_returns'],
                    'clock and period output counts agree')


def controls(clocks, observed):
    mutations = []
    c = copy.deepcopy(clocks); del c['schedules']['burst']['triton-fifo-graph32']
    mutations.append((c, observed))
    c = copy.deepcopy(clocks); c['schedules']['smooth']['nodus-causal-whole']['foreground'].pop()
    mutations.append((c, observed))
    c = copy.deepcopy(clocks); c['schedules']['smooth']['nodus-causal-whole']['batches'][0]['returns'].pop()
    mutations.append((c, observed))
    o = copy.deepcopy(observed); o['windows'][1] = copy.deepcopy(o['windows'][0])
    mutations.append((clocks, o))
    o = copy.deepcopy(observed); o['windows'][6]['formal_arm_status'] = 'complete'
    mutations.append((clocks, o))
    o = copy.deepcopy(observed); o['windows'][7]['original_scoring'] = 'verified'
    mutations.append((clocks, o))
    for c, o in mutations:
        try:
            validate(c, o)
        except ValueError:
            continue
        raise AssertionError('changed scientific scope was accepted')
    return len(mutations)


def replay(source, output, self_test=False):
    raw = Path(source).read_bytes()
    require(len(raw) == 475279 and hashlib.sha256(raw).hexdigest() == ZIP_SHA, 'fixed public archive')
    with zipfile.ZipFile(io.BytesIO(raw)) as archive:
        names = archive.namelist()
        require(len(names) == len(set(names)) == 19 and
                sum(i.file_size for i in archive.infolist()) < 3 * 1024**2, 'finite original census')
        require(all(not Path(n).is_absolute() and '..' not in Path(n).parts for n in names), 'safe names')
        members = {n: archive.read(n) for n in names}
    require(members['client-idle/matched-clocks.json'] == members['paired-waves/matched-clocks.json'],
            'same paired clock source')
    require(hashlib.sha256(members['client-idle/matched-clocks.json']).hexdigest() == CLOCK_SHA,
            'original clock SHA')
    clocks = json.loads(members['client-idle/matched-clocks.json'])
    observed = json.loads(members['period-output/observed-periods.json'])
    validate(clocks, observed)
    negatives = controls(clocks, observed) if self_test else None
    # These are the three fixed, hash-authenticated original reducers, not downloaded code.
    with tempfile.TemporaryDirectory(prefix='matched-triton-') as temp:
        root = Path(temp)
        for name, data in members.items():
            p = root / name; p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(data)
        commands = [('client-idle/compare.py', []),
                    ('paired-waves/paired_waves.py', [str(root/'paired-waves/matched-clocks.json')]),
                    ('period-output/period_output.py', [])]
        for script, args in commands:
            completed = subprocess.run([sys.executable, str(root/script), *args],
                                       timeout=15, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            require(completed.returncode == 0,
                    script+' failed: '+completed.stderr.decode(errors='replace')[-4096:])
        for name in ('client-idle/comparison.csv', 'paired-waves/all-paired-waves.csv',
                     'paired-waves/summary.csv', 'period-output/all-period-targets.csv'):
            require((root/name).read_bytes() == members[name], 'exact independent CSV replay: '+name)
    def rows(name):
        return list(csv.DictReader(io.StringIO(members[name].decode())))
    dispositions = [{k: v for k, v in row.items() if not isinstance(v, (list, dict))}
                    for row in observed['windows']]
    result = dict(schema='nodus.public-matched-triton-replay/1', producer_run=44537351420,
                  original_formal_comparison_accepted=False, descriptive_only=True,
                  matched=rows('client-idle/comparison.csv'), paired=rows('paired-waves/summary.csv'),
                  period_targets=rows('period-output/all-period-targets.csv'),
                  all_window_dispositions=dispositions, negative_controls=negatives)
    Path(output).parent.mkdir(parents=True, exist_ok=True)
    Path(output).write_text(json.dumps(result, indent=2)+'\n')
    print('Matched Triton original replay PASS: 8 matched rows, 6 paired summaries, 18 dispositions;'
          f' negative controls={negatives}')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('archive'); parser.add_argument('output')
    parser.add_argument('--self-test', action='store_true')
    args = parser.parse_args()
    replay(args.archive, args.output, args.self_test)
