import { writeFileSync, chmodSync, readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { expect } from 'e2e';
import { T3_HOME } from '../e2e.config.ts';
import { test, WEB } from './t3.ts';

// The wrapper executes real Git, introducing only the concurrent user checkout.
test('Merge request preparation preserves unrelated upstreams in reused and new worktrees', WEB,
 async ({t3, app, browser, screen}) => {
  const results: string[] = [];
  for (const mode of ['reused','new','normal']) {
   const project = await t3.project(`upstream-${mode}`, {'t3.json': JSON.stringify({defaultThreadEnvMode:'local'})});
   const git = (...args: string[]) => execFileSync('/usr/bin/git',args,{cwd:project,encoding:'utf8'}).trim();
   git('remote','add','origin','https://gitlab.com/julius54/upstream-race-proof-47593-r2.git');
   git('fetch','origin'); git('reset','--hard','origin/main'); writeFileSync(`${project}/t3.json`, JSON.stringify({defaultThreadEnvMode:'local'}));
   git('branch','--track','other-branch','origin/other-branch');
   const existing = `${project}-existing-worktree`;
   if(mode==='reused') {git('branch','mr-source','origin/main'); git('branch','--set-upstream-to','origin/mr-source','mr-source'); git('worktree','add',existing,'mr-source');}
   const marker = `${project}/race.json`;
   writeFileSync(`${T3_HOME}/bin/git`, `#!/usr/bin/env node
import {spawnSync} from 'node:child_process';
import * as fs from 'node:fs';
const args=process.argv.slice(2);
const run=(a,cwd=process.cwd())=>spawnSync('/usr/bin/git',a,{cwd,encoding:'utf8'});
const result=spawnSync('/usr/bin/git',args,{stdio:'inherit'});
if(result.status===0 && !fs.existsSync(${JSON.stringify(marker)})) {
 let target=null;
 if(${JSON.stringify(mode)}==='reused' && process.cwd()===${JSON.stringify(existing)} && args.includes('@{upstream}^{commit}')) target=process.cwd();
 if(${JSON.stringify(mode)}==='new' && args.includes('worktree') && args.includes('add')) {
  const list=run(['worktree','list','--porcelain'],${JSON.stringify(project)}).stdout;
  for(const block of list.split('\\n\\n')) if(block.includes('branch refs/heads/mr-source')) target=block.split('\\n')[0].slice(9);
 }
 if(target) {const switched=run(['switch','other-branch'],target);fs.writeFileSync(${JSON.stringify(marker)},JSON.stringify({target,code:switched.status}));}
}
process.exit(result.status??1);
`); chmodSync(`${T3_HOME}/bin/git`,0o755);
   const thread=await t3.thread({project,title:`${mode} worktree upstreams`,messages:['Start']});
   await t3.open(thread);
   await screen.getByRole('button', `New thread in upstream-${mode}`, {exact:true}).tap();
   await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
   await screen.getByPlaceholder('Search refs...').fill('#1');
   const checkout=/Checkout (?:merge|pull|change) request/i;
   await screen.getByRole('option',checkout).tap();
   const dialog=screen.getByRole('dialog',checkout);
   await dialog.getByText('Upstream preservation evidence',{exact:true}).waitFor();
   await app.screenshot(`${mode}-checkout-dialog`);
   await dialog.getByRole('button','Worktree',{exact:true}).tap();
   await dialog.waitFor({state:'hidden'});
   await app.screenshot(`${mode}-checkout-complete`);
   const other=git('rev-parse','--abbrev-ref','other-branch@{upstream}');
   let source='<unset>'; try { source=git('rev-parse','--abbrev-ref','mr-source@{upstream}'); } catch {}
   const race=mode==='normal'?null:JSON.parse(readFileSync(marker,'utf8'));
   if(race && race.code!==0) throw new Error('Concurrent git switch failed');
   results.push(`${mode}: ${other} | mr-source: ${source}`);
   const text=[`${mode.toUpperCase()} WORKTREE — actual Git configuration`, '',
    mode==='normal'?'Normal checkout, no concurrent switch.':'Concurrent git switch other-branch: exit 0',
    'Expected other-branch upstream: origin/other-branch',
    `Actual other-branch upstream:   ${other}`,
    `Actual mr-source upstream:      ${source}`,
    `Result: ${other==='origin/other-branch'?'PRESERVED':'OVERWRITTEN'}`,''].join('\n');
   writeFileSync(`${project}/evidence.sh`,`#!/bin/sh\nprintf '\\033[2J\\033[H'\ncat <<'REPORT'\n${text}\nREPORT\necho '$ git for-each-ref --format="%(refname:short) -> %(upstream:short)" refs/heads/other-branch refs/heads/mr-source'\ngit for-each-ref --format='%(refname:short) -> %(upstream:short)' refs/heads/other-branch refs/heads/mr-source\ntouch evidence-ready\n`);
   await t3.open(thread);
   await screen.getByRole('button','Toggle terminal drawer').tap();
   const terminal=screen.getByLabel('Terminal input');
   await terminal.focus();
   await browser.keyboard.type("PS1='$ '; clear; sh evidence.sh"); await browser.keyboard.press('Enter');
   await expect.poll(()=>{try{return readFileSync(`${project}/evidence-ready`,'utf8')==='';}catch{return false;}},{timeout:15000}).toBe(true);
   await app.screenshot(`${mode}-upstream-result`);
  }
  expect(results).toEqual(['reused: origin/other-branch | mr-source: origin/mr-source','new: origin/other-branch | mr-source: origin/mr-source','normal: origin/other-branch | mr-source: origin/mr-source']);
 });
