import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync, chmodSync } from "node:fs";
import { createServer } from "node:net";
import { APP_DIR } from "../e2e.config.ts";
export const cli = (home:string,args:string[])=>execFileSync(process.execPath,["apps/server/src/bin.ts",...args,"--base-dir",home],{cwd:APP_DIR,encoding:"utf8",env:{...process.env,T3CODE_DEV_SEED:"0"}});
export async function peer(parent:string,label="Scenario"){
 const home=`${parent}/peer-${label.replaceAll(" ","-")}`;
 mkdirSync(`${home}/userdata`,{recursive:true});
 writeFileSync(`${home}/userdata/settings.json`,JSON.stringify({linkedEnvironmentsEnabled:true}));
 mkdirSync(`${home}/bin`,{recursive:true});
 for(const command of ["hostnamectl","scutil"]){const file=`${home}/bin/${command}`;writeFileSync(file,`#!/bin/sh\necho '${label}'\n`);chmodSync(file,0o755);}
 const port=await new Promise<number>(r=>{const s=createServer();s.listen(0,"127.0.0.1",()=>{const p=(s.address() as any).port;s.close(()=>r(p));});});
 const child=spawn(process.execPath,["apps/server/src/bin.ts","serve","--base-dir",home,"--host","127.0.0.1","--port",String(port)],{cwd:APP_DIR,env:{...process.env,T3CODE_DEV_SEED:"0",T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD:"0",PATH:`${home}/bin:${parent}/bin:${process.env.PATH}`},stdio:"ignore"});
 const stop=async()=>{child.kill("SIGTERM");await new Promise<void>(r=>{if(child.exitCode!==null)r();else child.once("exit",()=>r());});};
 try {
  for(let i=0;;i++){try{if((await fetch(`http://127.0.0.1:${port}/.well-known/t3/environment`)).ok)break;}catch{}if(i>120)throw new Error("Peer startup failed");await new Promise(r=>setTimeout(r,250));}
  return {home,port,stop,link:()=>{const token=/Token:\s*(\S+)/.exec(cli(home,["pair"]))?.[1];if(!token)throw new Error("No token");return cli(parent,["environment","link",`http://127.0.0.1:${port}`,"--pairing-code",token,"--access","full-access"]);}};
 }catch(e){await stop();throw e;}
}
