import { chmod } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const fixture = `#!/usr/bin/env node
if (process.argv.includes('login')) {
  process.stdout.write('x'.repeat(520) + 'Login failed: token expired.\\r\\n', () => process.exit(1));
} else {
  let buffer = '';
  process.stdin.on('data', chunk => {
    buffer += chunk;
    let end;
    while ((end = buffer.indexOf('\\n')) >= 0) {
      const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
      if (!line.trim()) continue;
      const request = JSON.parse(line);
      if (request.id === undefined) continue;
      const response = request.method === 'initialize'
        ? {result: {protocolVersion: 1, agentCapabilities: {}, authMethods: [{id:'terminal', name:'Terminal login', type:'terminal', args:['login']}]}}
        : {error: {code:-32000, message:'Authentication required'}};
      process.stdout.write(JSON.stringify({jsonrpc:'2.0', id:request.id, ...response}) + '\\n');
    }
  });
}
`;

test("Terminal login keeps the final diagnostic character", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("login-proof", {"login-agent.cjs": fixture});
  await chmod(`${project}/login-agent.cjs`, 0o755);
  await t3.open("/settings/providers");
  await screen.getByRole("button", "Add provider", {exact:true}).first().tap();
  await screen.getByRole("button", "Show more", {exact:true}).tap();
  await screen.getByRole("button", "Local ACP command", {exact:true}).tap();
  await screen.getByRole("textbox", "Executable", {exact:true}).fill(`${project}/login-agent.cjs`);
  await screen.getByRole("button", "Next", {exact:true}).tap();
  await screen.getByRole("button", "Add instance", {exact:true}).tap();
  await screen.getByRole("button", "Sign in", {exact:true}).tap();
  await screen.getByRole("button", "Retry sign-in", {exact:true}).waitFor();
  await app.screenshot("terminal-login-error");
  const diagnostic = await browser.evaluate(() => {
    const prefix = "The provider login command did not finish successfully.";
    const text = [...document.querySelectorAll('p')].map(p => p.textContent ?? '').find(t => t.startsWith(prefix)) ?? '';
    return text.slice(prefix.length).trim();
  });
  expect(diagnostic.endsWith("Login failed: token expired.") && diagnostic.length <= 500 && diagnostic.startsWith("…") && diagnostic.isWellFormed()).toBe(true);
});
