import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";
const ACP = `import { createInterface } from 'node:readline';
if (process.argv.includes('login')) {
 console.log('Connect to the VPN, then sign in again.');
 process.exit(1);
}
for await (const line of createInterface({input:process.stdin})) {
 const {id,method}=JSON.parse(line);
 if(id===undefined) continue;
 const reply=method==='initialize'
 ? {result:{protocolVersion:1,agentInfo:{name:'Fake Login Agent',version:'1.0.0'},agentCapabilities:{},authMethods:[{id:'login',name:'Terminal login',type:'terminal',args:['login']}]}}
 : {error:{code:-32000,message:'Authentication required'}};
 process.stdout.write(JSON.stringify({jsonrpc:'2.0',id,...reply})+'\\n');
}`;
test('Failed terminal sign-in preserves the printed reason', WEB, async ({t3,app,screen,browser})=>{
 await browser.emulateMedia({colorScheme:'dark'});
 const project=await t3.project('demo');
 const script=path.join(project,'fake-login.mjs');
 await fs.writeFile(script,ACP);
 const settingsPath=path.join(T3_HOME,'userdata/settings.json');
 const settings=JSON.parse(await fs.readFile(settingsPath,'utf8'));
 settings.providerInstances['fake-login']={driver:'acpRegistry',displayName:'Fake Login Agent',enabled:true,config:{source:'local',commandPath:"node",commandArgs:[script]}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 await t3.open('/settings/providers?instanceId=fake-login');
 await screen.getByRole('button','Sign in',{exact:true}).waitFor({timeout:60000});
 await screen.getByRole('button','Sign in',{exact:true}).tap();
 await screen.getByRole('button','Retry sign-in',{exact:true}).waitFor({timeout:60000});
 await app.screenshot('failed-terminal-sign-in');
 await expect(screen.getByText('The provider login command did not finish successfully. Connect to the VPN, then sign in again.',{exact:true})).toBeVisible();
});
