import * as Http from "node:http";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Changing the Antigravity account ends every in-flight run", WEB, async ({t3, app, screen, browser}) => {
  let requests = 0;
  const pending = Promise.withResolvers<void>();
  const restarted = Promise.withResolvers<void>();
  const endpoint = Http.createServer((req, res) => {
    if (req.url?.includes("streamGenerateContent")) { requests++; if (requests >= 2) pending.resolve(); if (requests >= 3) restarted.resolve(); req.resume(); }
    else { res.writeHead(200, {"Content-Type":"application/json"}); res.end(JSON.stringify({models: []})); }
  });
  await new Promise<void>(resolve => endpoint.listen(13998, "127.0.0.1", resolve));
  try {
    const project = await t3.project("Account recovery");
    const instanceId = ProviderInstanceId.make("antigravity");
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({patch: {}, providerInstanceMutation: {operation:"upsert", instanceId, instance:{driver:ProviderDriverKind.make("antigravity"), enabled:true, config:{authMethod:"gemini-api-key",apiKey:"scenario-key"}}}});
      yield* client["provider.auth.start"]({instanceId});
    }).pipe(Effect.scoped));
    const {cli} = makeState(T3_HOME);
    const threads: {threadId:string}[] = [];
    for (const title of ["First in-flight thread", "Second in-flight thread"]) {
      const started = await runPromise(cli(["thread","start",project,"Keep working until I return.","--title",title,"--provider","antigravity","--model","gemini-3.8-flash","--json"]));
      threads.push(JSON.parse(started.stdout));
    }
    await pending.promise;
    await t3.open(threads[0]);
    await screen.getByText("Keep working until I return.", {exact:true}).first().waitFor({timeout:60000});
    await screen.getByRole("button", "Stop generation").waitFor();
    await app.screenshot("two-runs-in-flight");
    await t3.open("/settings/providers?instanceId=antigravity");
    await screen.getByRole("button", "Change account", {exact:true}).tap({timeout:60000});
    await t3.open(threads[0]);
    await screen.getByText("Keep working until I return.", {exact:true}).first().waitFor({timeout:60000});
    let ended = false;
    try {
      await expect(screen.getByRole("button", "Stop generation")).toBeHidden({timeout:15000});
      ended = true;
    } finally {
      if (ended) await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
      await app.screenshot("run-after-change-account");
      const composer = browser.locator('[data-chat-composer-form="true"]');
      await composer.getByRole("textbox").fill("are you still there?");
      await composer.getByRole("textbox").press("Enter");
      if (ended) {
        await restarted.promise;
        await screen.getByRole("button", "Stop generation").waitFor();
      } else {
        await screen.getByText("is not active.", {exact:false}).first().waitFor();
      }
      await app.screenshot("follow-up-message");
    }
    await t3.open(threads[1]);
    await screen.getByText("Keep working until I return.", {exact:true}).first().waitFor({timeout:60000});
    await expect(screen.getByRole("button", "Stop generation")).toBeHidden();
    await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
    await app.screenshot("second-run-after-change-account");
  } finally { endpoint.close(); endpoint.closeAllConnections(); }
});
