import { expect } from 'e2e';
import { test, WEB, makeState, runPromise } from './t3.ts';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { run } from './shell.ts';
import { spawn } from 'node:child_process';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { resolve } from 'node:path';
import { createServer } from 'node:net';

test('IPv6 SCP origins select the equivalent SSH project in a linked environment', WEB, async ({t3,app,screen})=>{
 const home=resolve(T3_HOME,'peer');
 await mkdir(resolve(home,'userdata'),{recursive:true});
 const settings=JSON.parse(await readFile(resolve(T3_HOME,'userdata/settings.json'),'utf8'));
 settings.linkedEnvironmentsEnabled=true;
 await writeFile(resolve(T3_HOME,'userdata/settings.json'),JSON.stringify(settings));
 await writeFile(resolve(home,'userdata/settings.json'),JSON.stringify(settings));
 const port=await new Promise<number>(ok=>{const s=createServer();s.listen(0,'127.0.0.1',()=>{const p=(s.address() as any).port;s.close(()=>ok(p))})});
 const child=spawn(process.execPath,['scripts/dev-runner.ts','dev:server','--home-dir',home,'--no-seed','--port',String(port),'--dev-url',`http://127.0.0.1:${port+1}`],{cwd:APP_DIR,env:{...process.env,PATH:resolve(T3_HOME,'bin')+':'+process.env.PATH,T3CODE_DEV_SEED:'0',T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD:'0'},stdio:['ignore','pipe','pipe']});
 const ready=new Promise<void>((ok,bad)=>{child.stdout.on('data',d=>{if(String(d).includes('pairingUrl:'))ok()});child.on('exit',code=>bad(Error('Peer exited '+code)));});
 try {
 await ready;
 const cli=async(h:string,args:string[])=>JSON.parse((await runPromise(run(process.execPath,['apps/server/src/bin.ts',...args,'--base-dir',h],{cwd:APP_DIR}))).stdout);
 const other=makeState(home);
 await other.state.project('IPv6 destination',{'.git/config':'[remote "origin"]\n url = ssh://git@[2001:db8::1]/team/repo.git\n'});
 const pairing=await cli(home,['auth','pairing','create','--json']);
 await runPromise(run(process.execPath,['apps/server/src/bin.ts','environment','link',`http://127.0.0.1:${port}`,'--pairing-code',pairing.credential??pairing.token,'--access','full-access','--base-dir',T3_HOME],{cwd:APP_DIR,allowExit:[0,1]})).then(r=>{if(r.exitCode)throw Error(r.stdout+r.stderr)});
 const environment=await (await fetch(`http://127.0.0.1:${port}/.well-known/t3/environment`)).json();
 settings.providerInstances.devReplay.config.commandArgs=[resolve(import.meta.dirname,'ipv6-delegation-agent.mjs')];
 await writeFile(resolve(T3_HOME,'userdata/settings.json'),JSON.stringify(settings));
 const variants=['git@[2001:db8::1]:team/repo.git','[2001:db8::1]:team/repo.git','git@[2001:DB8:0::1]:team/repo.git'];
 const outcomes=[];
 for(const [i,remote] of variants.entries()) {
   const project=await t3.project(`IPv6 source ${i+1}`,{'.git/config':`[remote "origin"]\n url = ${remote}\n`,'.proof.json':JSON.stringify({environmentId:environment.environmentId,remote})});
   const thread=await t3.thread({project,title:`IPv6 repository lookup ${i+1}`,messages:['Delegate to the linked destination without specifying target.projectId.'],model:'showcase'});
   await t3.open(thread);
   await screen.getByText('REMOTE LOOKUP',{exact:false}).first().waitFor({state:'visible'});
   await screen.getByText('Syncing messages...', {exact:false}).waitFor({state:'hidden'});
   await app.screenshot(`ipv6-lookup-${i+1}`);
   outcomes.push(await screen.getByText('REMOTE LOOKUP SUCCEEDED',{exact:false}).count());
 }
 await expect(outcomes).toEqual([1,1,1]);
 } finally {child.kill('SIGTERM');await new Promise<void>(ok=>child.once('exit',()=>ok()));}
});
