import { expect } from "e2e";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { codexAuthDeliveryUrl } from "@t3tools/shared/codexAuthHandoff";
import { spawn } from "node:child_process";
import { createServer } from "node:net";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { prepareHome } from "./start-app.ts";

async function startDestination(devUrl: string) {
  const home = `${T3_HOME}-destination`;
  await runPromise(prepareHome(home));
  const reservation = createServer();
  await new Promise<void>(resolve => reservation.listen(0, "127.0.0.1", resolve));
  const port = (reservation.address() as {port:number}).port;
  await new Promise<void>(resolve => reservation.close(() => resolve()));
  const child = spawn(process.execPath, ["apps/server/src/bin.ts", "serve", "--host", "127.0.0.1", "--port", String(port), "--base-dir", home, "--dev-url", devUrl], {cwd:APP_DIR, env:{PATH:`${home}/bin:${process.env.PATH}`,HOME:process.env.HOME,T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD:"0",T3CODE_DEV_SEED:"0"},stdio:["ignore","pipe","inherit"]});
  const ready = new Promise<{host:string;token:string}>((resolve,reject) => {
    let output = "";
    child.stdout.on("data", chunk => { output += chunk; const token = /^Token:\s*(\S+)/m.exec(output)?.[1]; if(token) resolve({host:`http://127.0.0.1:${port}`,token}); });
    child.once("exit", code => reject(new Error(`Destination exited: ${code}`)));
  });
  return {ready, stop: async () => {if(child.exitCode === null) {child.kill("SIGTERM"); await new Promise(resolve => child.once("exit",resolve));}}};
}
import { environmentId, runPromise, test, WEB } from "./t3.ts";

test("ChatGPT return to a removed environment reports the unavailable destination", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("demo");
  const server = await startDestination(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    const destination = await runPromise(environmentId(host));
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    const actions = screen.getByRole("button", "More actions for Scenario");
    await actions.waitFor({ timeout: 60_000 });
    await screen.getByText("Connected", { exact: false }).first().waitFor({ timeout: 60_000 });
    const authorization = new URL("https://auth.openai.com/api/accounts/authorize");
    for (const [key, value] of Object.entries({redirect_uri:"http://127.0.0.1:1455/auth/callback",state:"synthetic-state-123456",response_type:"code",code_challenge_method:"S256",code_challenge:"a".repeat(43),client_id:"dynamic_agent_client"})) authorization.searchParams.set(key,value);
    const delivery = codexAuthDeliveryUrl({ authorizationUrl: authorization.toString(), returnUrl: `${app.baseUrl}/welcome#agents:${destination}`, environmentId: EnvironmentId.make(destination), instanceId: ProviderInstanceId.make("codex"), flowId: "synthetic-flow" }, "http://127.0.0.1:1455/auth/callback?state=synthetic-state-123456&code=synthetic-code");
    await app.open(delivery);
    await screen.getByText("Return to the provider and try again.", {exact:true}).waitFor({timeout:60_000});
    await app.open("/settings/connections");
    await actions.press("Enter");
    await screen.getByRole("menuitem", "Remove from this device…").press("Enter");
    await screen.getByRole("button", "Confirm").press("Enter");
    await actions.waitFor({state:"hidden"});
    await screen.getByText("No saved remote environments", {exact:true}).waitFor();
    await app.open(delivery);
    await expect(browser).not.toHaveURL(/codex-auth=/);
    try {
      await expect(screen.getByText("Reconnect to the environment and try again.", {exact:true})).toBeVisible({timeout:40_000});
    } finally {
      await app.screenshot("removed-environment-return");
    }
  } finally { await server.stop(); }
});
