import { execFileSync, spawnSync } from 'node:child_process';
import { writeFileSync, existsSync, watch } from 'node:fs';
import { createHash, randomUUID } from 'node:crypto';
import * as Effect from 'effect/Effect';
import { CommandId, ThreadId } from '@t3tools/contracts';
import { expect } from 'e2e';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { rpcClient, runPromise, test, WEB } from './t3.ts';

const until = (directory: string, check: () => boolean) => new Promise<void>((resolve,reject)=>{
  const watcher = watch(directory,{recursive:true},()=>{if(check()){clearTimeout(timer);watcher.close();resolve();}});
  const timer=setTimeout(()=>{watcher.close();reject(new Error('Scenario setup did not complete'));},60000);
  if(check()){clearTimeout(timer);watcher.close();resolve();}
});
const hash = (data: Uint8Array) => createHash('sha256').update(data).digest('hex');
test('Checkpoint LFS objects restore with whitespace in lfs.storage and no watching client', WEB, async ({t3,app,browser,screen}) => {
  const evidenceProject = await t3.project('LFS-proof');
  const evidenceThread = await t3.thread({project:evidenceProject,title:'Checkpoint LFS restore evidence',messages:['Start']});
  const sha = execFileSync('git',['rev-parse','HEAD'],{cwd:APP_DIR,encoding:'utf8'}).trim();
  const report: string[] = [`CHECKPOINT LFS RESTORE — ${sha.slice(0,10)}`, `Linux / ${execFileSync('git',['lfs','version'],{encoding:'utf8'}).trim()} / Replay`, 'Fresh repos; no browser watching when turns end.', '4096-byte payload created while Question turn waits.', ''];
  const results: boolean[] = [];
  for (const [name, storage] of [['trailing space','object cache '],['trailing tab','object cache\t'],['leading space',' object cache'],['default',null]] as const) {
    const project = await t3.project(`lfs-${name.replaceAll(' ','-')}`);
    const git = (...args:string[]) => execFileSync('git',args,{cwd:project,encoding:'utf8'});
    git('lfs','install','--local');
    git('lfs','track','*.bin');
    git('add','.gitattributes');
    git('-c','user.name=Scenario','-c','user.email=scenario@example.invalid','commit','-qm','Track binaries');
    if(storage !== null) git('config','--local','lfs.storage',storage);
    const thread = await t3.thread({project,title:name,messages:['Ask me something'],model:'question'});
    const payload = Buffer.from(Array.from({length:4096},(_,i)=>(i*73+19)%256));
    writeFileSync(`${project}/payload.bin`,payload);
    await runPromise(Effect.gen(function*(){
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? '');
      const projection = yield* client['orchestration.getThreadProjection']({threadId:ThreadId.make(thread.threadId)});
      const request = projection.runtimeRequests.find(r=>r.status==='pending');
      if (!request) throw new Error('No pending Replay question');
      yield* client['orchestration.dispatchCommand']({type:'runtime-request.respond',commandId:CommandId.make(randomUUID()),threadId:ThreadId.make(thread.threadId),requestId:request.id,answers:{schema_vs_ui_flexibility:'Strict schemas (Recommended)'}});
    }).pipe(Effect.scoped));
    let ref = '';
    await until(`${project}/.git/refs`, () => {
      ref = git('for-each-ref','--format=%(refname)','refs/t3/orchestration-v2/checkpoints').split('\n').find(r=>r.endsWith('/ordinal/1')) ?? '';
      return ref.length > 0;
    });
    const pointer = git('cat-file','-p',`${ref}:payload.bin`);
    const smudged = spawnSync('git',['-c','core.quotepath=false','lfs','smudge','payload.bin'],{cwd:project,input:pointer});
    const exact = existsSync(`${project}/.git/${storage ?? 'lfs'}/objects/${hash(payload).slice(0,2)}/${hash(payload).slice(2,4)}/${hash(payload)}`);
    const ok = smudged.status === 0 && hash(smudged.stdout) === hash(payload) && exact;
    results.push(ok);
    report.push(`${name}: ${JSON.stringify(storage ?? '(default)')}  ${ok?'PASS':'FAIL'}`, `  object exists=${exact}  smudge exit=${smudged.status}  bytes match=${hash(smudged.stdout) === hash(payload)}`);
  }
  writeFileSync(`${evidenceProject}/proof.txt`,report.join('\n')+'\n');
  writeFileSync(new URL(`../.e2e/prove/restore-${sha.slice(0,10)}.txt`,import.meta.url),report.join('\n')+'\n');
  console.log(report.join('\n')+'\n');
  await t3.open(evidenceThread);
  await screen.getByRole('button','Toggle terminal drawer').tap();
  const input=screen.getByRole('textbox','Terminal input');
  await input.waitFor();
  await browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]').waitFor();
  await input.focus();
  await browser.keyboard.type("PS1='proof $ '; clear; cat proof.txt; touch shown\n");
  await until(evidenceProject,()=>existsSync(`${evidenceProject}/shown`));
  await app.screenshot('checkpoint-lfs-restore');
  expect(results).toEqual([true,true,true,true]);
});
