import os, sys, subprocess, pathlib, datetime, sqlite3, re
root=pathlib.Path(__file__).resolve().parent
run=root/('run-'+datetime.datetime.now().strftime('%Y%m%dT%H%M%S'))
run.mkdir()
for side, checkout in zip(('before','after'),sys.argv[1:]):
    checkout=pathlib.Path(checkout).resolve()
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    lines=[f'{side.upper()} | commit {sha}', 'Environment: Linux x86_64; Node '+subprocess.check_output(['node','--version'],text=True).strip(), 'Real CLI source entrypoint; fresh isolated state per case.','Paths below use <case> in place of the temporary run directory.','']
    for label,arg,folder in [('empty','', 'myfolder'),('spaces','   ','myfolder2')]:
        case=run/side/label; cwd=case/folder; cwd.mkdir(parents=True); state=case/'state'
        env=dict(os.environ,T3CODE_DEV_SEED='0',NO_COLOR='1')
        p=subprocess.run(['node',str(checkout/'apps/server/src/bin.ts'),'project','add',arg,'--base-dir',str(state)],cwd=cwd,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        output=p.stdout.replace(str(case),'<case>').replace(str(checkout),'<checkout>')
        lines += [f'Case: {label}; cwd=<case>/{folder}',f'$ t3 project add "{arg}" --base-dir <case>/state',output.strip(),f'Exit code: {p.returncode}']
        dbs=list(state.rglob('statev2.sqlite')) if state.exists() else []
        if dbs:
            with sqlite3.connect(f'file:{dbs[0]}?mode=ro',uri=True) as db:
                rows=db.execute('SELECT title, workspace_root FROM projection_projects').fetchall()
            lines += [f'projection_projects row count: {len(rows)}']
            for title,path in rows: lines.append(f'  title={title}; workspace_root={path.replace(str(case),"<case>")}')
        else: lines += ['No state database created; no project persisted.']
        lines += ['']
    transcript='\n'.join(lines)
    (run/(side+'.txt')).write_text(transcript)
    print(transcript)
print('ARTIFACT_DIR='+str(run))
