#!/usr/bin/env python3
"""Measure default ptop against vtop with the reviewed ptop PTY harness.

Requires scripts/benchmark.py and scripts/compare_monitors.py from ptop commit
e4c4067e3a862646c93c59152cda5e8fc3b72d0e. Output ends in a completion record.
No terminal content, process names, PIDs, hostnames or local paths are recorded.
"""
import argparse
import datetime
import hashlib
import json
import os
from pathlib import Path
import platform
import shutil
import subprocess
import sys
import tempfile


def dependency_lock(root):
    # npm's global install retained no npm lock. Pin the actual installed bytes
    # rather than resolving a new dependency tree and pretending it was tested.
    rows = []
    for path in sorted(root.rglob('*')):
        if path.is_file():
            rows.append(dict(file=path.relative_to(root).as_posix(),
                             sha256=hashlib.sha256(path.read_bytes()).hexdigest()))
    return json.dumps(dict(kind='installed vtop file manifest; not an npm resolution lock',
                           files=rows), sort_keys=True, separators=(',', ':')).encode()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--harness-dir', required=True, type=Path)
    parser.add_argument('--ptop', required=True, type=Path)
    parser.add_argument('--vtop', required=True, type=Path)
    parser.add_argument('--node', required=True, type=Path)
    parser.add_argument('--dependency-lock-out', required=True, type=Path)
    parser.add_argument('--seconds', type=float, default=30)
    parser.add_argument('--pairs', type=int, default=4)
    options = parser.parse_args()
    sys.path.insert(0, str(options.harness_dir.resolve()))
    import benchmark
    from compare_monitors import hardware, isolated_environment

    if sys.platform != 'darwin' or not 1 <= options.pairs <= 100:
        raise RuntimeError('use macOS and 1..100 pairs')
    seconds = benchmark.duration(str(options.seconds))
    binaries = {label: getattr(options, label).resolve() for label in ('ptop', 'vtop', 'node')}
    if any(not path.is_file() or not os.access(path, os.X_OK) for path in binaries.values()):
        raise RuntimeError('executables are required')
    revision = subprocess.check_output(
        ['git', '-C', str(options.harness_dir.resolve().parent), 'rev-parse', 'HEAD'], text=True).strip()
    if revision != 'e4c4067e3a862646c93c59152cda5e8fc3b72d0e':
        raise RuntimeError('the reviewed harness revision is required')
    vtop_root = binaries['vtop'].parent.parent
    if json.loads((vtop_root / 'package.json').read_text())['version'] != '0.6.1':
        raise RuntimeError('expected vtop 0.6.1')
    lock = dependency_lock(vtop_root)
    options.dependency_lock_out.write_bytes(lock + b'\n')
    lock_hash = hashlib.sha256(lock + b'\n').hexdigest()

    def environment(root):
        env = isolated_environment(root)
        env['PATH'] = str(binaries['node'].parent) + ':/usr/bin:/bin:/usr/sbin:/sbin'
        selected = shutil.which('ps', path=env['PATH'])
        if not selected or Path(selected).resolve() != Path('/bin/ps'):
            raise RuntimeError('system ps is required for native ptop collection')
        return env

    with tempfile.TemporaryDirectory(prefix='ptop-vtop-version-') as directory:
        env = environment(Path(directory))
        tools = {label: dict(version=benchmark.version(path, env), sha256=benchmark.digest(path))
                 for label, path in binaries.items()}
    if tools['ptop']['version'] != '0.1.3' or tools['vtop']['version'] != '0.6.1':
        raise RuntimeError('expected ptop 0.1.3 and vtop 0.6.1')
    info = dict(record='metadata', schema=1, experiment='ptop-0.1.3-default-vs-vtop-0.6.1',
                utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),
                macos=platform.mac_ver()[0], architecture=platform.machine(), hardware=hardware(),
                python=platform.python_version(), tools=tools,
                adapter_sha256=benchmark.digest(Path(__file__)), harness_revision=revision,
                measurement_harness_sha256=benchmark.digest(Path(benchmark.__file__)),
                configuration_harness_sha256=benchmark.digest(options.harness_dir / 'compare_monitors.py'),
                vtop_dependency_lock=dict(kind='installed file manifest; no retained npm lockfile',
                                          sha256=lock_hash, files=len(json.loads(lock)['files'])),
                pairs=options.pairs, requested_seconds=seconds, cols=100, rows=30,
                interval_ms=300, theme='parallax', mouse=False, term='xterm-256color',
                locale='en_US.UTF-8', ptop_mode='default; no --vtop-parity or --fix',
                order='vtop/ptop on even pairs, ptop/vtop on odd pairs',
                config_scope='fresh XDG config/state/cache and HTOPRC each run; pinned Node plus system PATH',
                cpu_scope='wait4 user+system: monitor plus reaped children; launch/exit included; 100%=one core',
                memory_scope='monitor own RSS sampled after first output; per-run mean; children excluded',
                timing_scope='30 requested seconds by default; no warmup exclusion; elapsed includes shutdown',
                background_scope='normal existing user applications retained; no builds or tests during measurement',
                completion_required=True)
    print(json.dumps(info), flush=True)
    resident = benchmark.ResidentMemory()
    for sequence, (pair, label) in enumerate(benchmark.orders(options.pairs)):
        for item in (label, 'node'):
            if benchmark.digest(binaries[item]) != tools[item]['sha256']:
                raise RuntimeError('an executable changed; discard results')
        with tempfile.TemporaryDirectory(prefix='ptop-vtop-run-') as directory:
            env = environment(Path(directory))
            args = [str(binaries[label]), '--update-interval', '300', '--no-mouse', '--theme', 'parallax']
            metrics = benchmark.run(args, env, seconds, 100, 30, resident)
        if benchmark.digest(binaries[label]) != tools[label]['sha256']:
            raise RuntimeError('an executable changed; discard results')
        print(json.dumps(dict(record='run', tool=label, pair=pair, sequence=sequence, **metrics)), flush=True)
    if dependency_lock(vtop_root) != lock or benchmark.digest(binaries['node']) != tools['node']['sha256']:
        raise RuntimeError('runtime or dependencies changed; discard results')
    print(json.dumps(dict(record='complete', runs=2 * options.pairs, dependency_lock_verified=True)), flush=True)


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted; discard partial results.', file=sys.stderr)
        sys.exit(130)
    except Exception:
        print('Measurement failed; discard partial results. Check executables and harness inputs.', file=sys.stderr)
        sys.exit(1)
