#!/usr/bin/env python3
"""Collect one bounded benchmark run. Python 3.10+, standard library only."""
import argparse
import datetime as dt
import hashlib
import json
import math
import os
from pathlib import Path
import platform
import statistics
import subprocess

ROOT = Path(__file__).resolve().parent
CONFIGS = {'locality': [4096, 65536, 1048576], 'sharing': [2, 4], 'allocation': [32, 256, 2048]}
VARIANTS = {'locality': ['shuffled', 'sequential'], 'sharing': ['packed', 'padded'], 'allocation': ['fresh', 'reuse']}

def validate(rows):
    expected_keys = {(name, config, variant, trial)
                     for name, configs in CONFIGS.items() for config in configs
                     for variant in VARIANTS[name] for trial in range(7)}
    seen = set()
    for row in rows:
        key = (row['experiment'], row['config'], row['variant'], row['trial'])
        if key not in expected_keys or key in seen:
            raise ValueError('unexpected or duplicate sample')
        seen.add(key)
        name, size, variant, _ = key
        ms = row['ms']
        if type(ms) not in (int, float) or not math.isfinite(ms) or ms <= 0:
            raise ValueError('invalid duration')
        if name == 'locality':
            checksum = size * (size + 1) // 2 * max(1, 2097152 // size)
        elif name == 'sharing':
            checksum = size * 1000000
        else:
            checksum = 10000 * size * (size - 1) // 2 + size * 10000 * 9999 // 2
        if row['checksum'] != str(checksum):
            raise ValueError('incorrect checksum')
        allocations = 10000 if name == 'allocation' and variant == 'fresh' else 0
        if type(row['allocations']) is not int or row['allocations'] != allocations:
            raise ValueError('incorrect allocation count')
    if seen != expected_keys:
        raise ValueError('missing samples')

def summarize(rows):
    validate(rows)
    groups = []
    for name, configs in CONFIGS.items():
        for config in configs:
            variants = []
            for variant in VARIANTS[name]:
                samples = sorted([r for r in rows if r['experiment'] == name and r['config'] == config and r['variant'] == variant], key=lambda r: r['trial'])
                times = [r['ms'] for r in samples]
                variants.append({'id': variant, 'median_ms': statistics.median(times),
                                 'min_ms': min(times), 'max_ms': max(times), 'samples': samples})
            groups.append({'experiment': name, 'config': config, 'variants': variants})
    return groups

def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def optional_text(path):
    try:
        return Path(path).read_text().strip()
    except OSError:
        return None

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--binary', type=Path, default=ROOT / 'build/perf-playground')
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--compiler', default='c++')
    args = parser.parse_args()
    binary = args.binary.resolve()
    # Exclusive create prevents accidentally replacing historical evidence.
    if args.output.exists():
        parser.error('output exists; choose a new evidence filename')
    started = dt.datetime.now(dt.timezone.utc).isoformat()
    result = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=180)
    rows = [json.loads(line) for line in result.stdout.splitlines() if line.strip()]
    groups = summarize(rows)
    cpu = next((s.split(':', 1)[1].strip() for s in (optional_text('/proc/cpuinfo') or '').splitlines() if s.startswith('model name')), platform.machine())
    report = {'schema_version': 1, 'started_at': started,
              'finished_at': dt.datetime.now(dt.timezone.utc).isoformat(),
              'environment': {'cpu': cpu, 'platform': platform.platform(),
                              'logical_cpus': os.cpu_count(),
                              'affinity_cpus': sorted(os.sched_getaffinity(0)) if hasattr(os, 'sched_getaffinity') else None,
                              'cgroup_cpu_max': optional_text('/sys/fs/cgroup/cpu.max'),
                              'compiler': subprocess.run([args.compiler, '--version'], capture_output=True, text=True, check=True).stdout.splitlines()[0],
                              'cmake_cache_sha256': sha(binary.parent / 'CMakeCache.txt') if (binary.parent / 'CMakeCache.txt').exists() else None,
                              'compiler_flags': next((s.split('=', 1)[1].strip() for s in (optional_text(binary.parent / 'CMakeFiles/perf-playground.dir/flags.make') or '').splitlines() if s.startswith('CXX_FLAGS =')), None),
                              'reported_cache_line_bytes': optional_text('/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size'),
                              'controls': 'Shared virtualized container. Affinity, frequency, power policy and physical-core placement uncontrolled. Other tenants may affect timings.'},
              'method': {'trials': 7, 'warmup_pairs': 2, 'order': 'alternating variant order each trial',
                         'clock': 'std::chrono::steady_clock', 'locality_target_visits': 2097152,
                         'locality_node_bytes': 16, 'shuffle_seed': 42,
                         'sharing_increments_per_worker': 1000000,
                         'sharing_slot_bytes': 128, 'allocation_batches': 10000,
                         'allocation_element_bytes': 8,
                         'scope': 'Wall time per entire workload, not per operation. Setup excluded; warm caches. Barrier release/completion included for sharing, creation/join excluded. Reuse buffer pre-reserved.'},
              'source_sha256': {name: sha(ROOT / name) for name in ['bench.cpp', 'CMakeLists.txt', 'collect.py']},
              'binary_sha256': sha(binary), 'groups': groups}
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open('x') as f:
        json.dump(report, f, indent=2, allow_nan=False)
        f.write('\n')
    print(f'Wrote {len(rows)} verified samples across {len(groups)} configurations to {args.output}')

if __name__ == '__main__':
    main()
