import os, sys, subprocess, pathlib, datetime, re, json
root = pathlib.Path(__file__).parent
run = root / ('run-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S'))
run.mkdir()
for side, checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    target=run/side
    target.mkdir()
    cache=target/'cache-file'; cache.touch()
    summary=target/'step-summary.md'; summary.touch()
    env=dict(os.environ,VITE_CACHE_PATH=str(cache),GITHUB_STEP_SUMMARY=str(summary),NO_COLOR='1',FORCE_COLOR='0')
    command=['node','scripts/test-cached.ts','--verify-hits','1','scripts/lib/sharded-tests.test.ts']
    result=subprocess.run(command,cwd=checkout,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    output=re.sub(r'\x1b\[[0-9;]*[a-zA-Z]','',result.stdout)
    output=output.replace(checkout,'<checkout>').replace(str(target),'<scratch>')
    report=f'{side.upper()} | commit {sha}\nLinux | Node '+subprocess.check_output(['node','--version'],text=True).strip()+' | real test:cached CLI\n\n'
    report+='Setup: empty ordinary cache-file; empty step-summary.md\n$ VITE_CACHE_PATH=<scratch>/cache-file GITHUB_STEP_SUMMARY=<scratch>/step-summary.md \\\n  node scripts/test-cached.ts --verify-hits 1 scripts/lib/sharded-tests.test.ts\n\n'
    report+=output+f'\nExit status: {result.returncode}\nStep summary: {summary.stat().st_size} bytes\n'
    report+='\n--- step-summary.md ---\n'+(summary.read_text() or '(empty)\n')
    (run/f'{side}.txt').write_text(report)
    print(report)
print('ARTIFACT_DIRECTORY='+str(run))
