#!/usr/bin/env python3
"""Run the real mobile:audit CLI against real device captures; record output and exit codes.
Usage: compare-driver.py CHECKOUT CAPTURE_ROOT OUTPUT_DIR LABEL
Capture baseline Threads and Settings, then candidate Settings using mobile:audit first.
Run once per checkout. After incomplete comparisons, capture candidate Threads and rerun
with the optional fifth argument 'complete' for the full-set control.
"""
import sys, pathlib, subprocess, re, json, datetime
checkout, captures, out, label = sys.argv[1:5]
root=pathlib.Path(out); root.mkdir(parents=True,exist_ok=True)
complete=len(sys.argv)>5
runs=[]
for gated in ([True] if complete else [True,False]):
    name='complete-control' if complete else ('incomplete-gated' if gated else 'incomplete-ungated')
    cmd=['vp','run','mobile:audit','compare','--before',str(pathlib.Path(captures)/'baseline'),'--after',str(pathlib.Path(captures)/'candidate'),'--out',str(root/name)]
    if gated: cmd.append('--fail-on-regression')
    p=subprocess.run(cmd,cwd=checkout,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output=re.sub(r'\x1b\[[0-9;]*m','',p.stdout)
    for private,public in [(checkout,'<checkout>'),(captures,'<captures>'),(out,'<output>')]: output=output.replace(private,public)
    # Error stack paths are private and add no evidence; retain the CLI error and exit.
    output='\n'.join(line for line in output.splitlines() if not re.match(r'\s+at ',line))
    text=f'{label} | {name}\n$ vp run mobile:audit compare --before baseline --after candidate --out diff'+(' --fail-on-regression' if gated else '')+'\n\n'+output+f'\n\nEXIT CODE: {p.returncode}\n'
    (root/(name+'.txt')).write_text(text)
    print(text,flush=True)
    runs.append({'name':name,'exitCode':p.returncode,'output':text})
(root/('complete.json' if complete else 'incomplete.json')).write_text(json.dumps(runs,indent=2))
