"""Finite actual-daemon collector; caller owns daemon through native Job launcher."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
from datetime import datetime, timezone

p = argparse.ArgumentParser()
p.add_argument('--run', type=Path, required=True)
p.add_argument('--binary', type=Path, required=True)
a = p.parse_args()
root = Path(__file__).resolve().parent.parent
run = a.run.resolve()
record = {'started_utc': datetime.now(timezone.utc).isoformat(), 'home': str(run / 'home'), 'binary': str(a.binary)}
try:
    args = ['powershell.exe', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', str(root / 'step1-collect.ps1'), '-Seconds', '60', '-HomePath', str(run / 'home'), '-Binary', str(a.binary)]
    record['collector_argv'] = args
    with (run / 'samples.jsonl').open('xb') as out, (run / 'collector.stderr').open('xb') as err:
        result = subprocess.run(args, stdout=out, stderr=err, timeout=75)
    record['collector_exit'] = result.returncode
    log = run / 'home' / 'logs' / 'daemon.stderr.log'
    data = log.read_bytes()
    if len(data) > 16 * 1024 * 1024:
        raise RuntimeError('daemon log exceeds bounded snapshot')
    (run / 'daemon.stderr.snapshot.log').write_bytes(data)
    record['log_sha256'] = hashlib.sha256(data).hexdigest()
    analyzer = root / 'raw-copy-resume-v1' / 'step1-analyze.py'
    digest = hashlib.sha256(analyzer.read_bytes()).hexdigest()
    assert digest == '6f36563c6882aed3d4d14f5b276531911d844f6c629b41963378f883a4e9ab24'
    record['analyzer_sha256'] = digest
    args = [sys.executable, str(analyzer), '--samples', str(run / 'samples.jsonl'), '--log', str(run / 'daemon.stderr.snapshot.log'), '--out', str(run / 'analysis')]
    record['analyzer_argv'] = args
    with (run / 'analyzer.stdout').open('xb') as out, (run / 'analyzer.stderr').open('xb') as err:
        result = subprocess.run(args, stdout=out, stderr=err, timeout=20)
    record['analyzer_exit'] = result.returncode
except BaseException as e:
    record['error'] = repr(e)
    raise
finally:
    # Signals the retained native job owner, never kills a daemon by PID.
    (run / 'stop').write_text('collection finished\n', encoding='utf-8')
    record['finished_utc'] = datetime.now(timezone.utc).isoformat()
    (run / 'collection.json').write_text(json.dumps(record, indent=2), encoding='utf-8')
    print(json.dumps(record))
