"""Use installed compilers only; explicit output directory. Never installs or deletes."""
import argparse, hashlib, json, platform, subprocess
from pathlib import Path

def verify(output, tsc):
    here=Path(__file__).resolve().parent; output=Path(output).resolve();output.mkdir(parents=True,exist_ok=True)
    def run(args, **kwargs): return subprocess.run(args,check=True,capture_output=True,text=True,**kwargs).stdout
    commands=[['node',str(tsc),'--strict','--target','ES2020','--module','commonjs','--outDir',str(output),str(here/'parse-count.ts')],['rustc','--edition=2021',str(here/'runner.rs'),'-o',str(output/'count-rust')]]
    for cmd in commands:run(cmd)
    vectors=json.loads((here/'vectors.json').read_text())
    wire=''.join(('missing' if v['input'] is None else 'hex:'+v['input'].encode().hex())+'\n' for v in vectors)
    ts=run(['node',str(here/'run.mjs'),str(output/'parse-count.js'),str(here/'vectors.json')])
    rust=run([str(output/'count-rust')],input=wire)
    results=[]
    for v,a,b in zip(vectors,ts.splitlines(),rust.splitlines(),strict=True):
        aa,bb=json.loads(a),json.loads(b);results.append({**v,'typescript':aa,'rust':bb,'passed':aa==bb==v['expected']})
    report={'kind':'observed test results','environments':{'node':run(['node','--version']).strip(),'typescript':run(['node',str(tsc),'--version']).strip(),'rustc':run(['rustc','--version']).strip(),'platform':platform.system()+' '+platform.release(),'architecture':platform.machine()},'source_sha256':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in here.iterdir() if p.is_file() and p.name not in ['RESULTS.json','README.md']},'commands':['node <existing-tsc> --strict --target ES2020 --module commonjs --outDir <output> parse-count.ts','rustc --edition=2021 runner.rs -o <output>/count-rust','node run.mjs <output>/parse-count.js vectors.json','<output>/count-rust < UTF-8 hex vectors (same inputs, same order)'],'cases':results,'passed':all(x['passed'] for x in results),'limits':'Finite vectors are evidence, not proof of equivalence for all inputs. No benchmark, integration test, or performance claim. Invalid UTF-8 and non-string/non-null inputs are outside the function contract.'}
    (output/'RESULTS.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
    if not report['passed']:raise AssertionError('behavior differs; retain RESULTS.json')
    print(f'{len(results)} vectors passed in both implementations')
if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--output',required=True);p.add_argument('--tsc',required=True);a=p.parse_args();verify(a.output,a.tsc)
