/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ThreadId } from "@t3tools/contracts";
import { mkdir, writeFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { T3_HOME } from "../e2e.config.ts";
import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A live floating Pixel 9 keeps its stream across thread and project switches", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("server");
  const other = await t3.project("web");
  const a = await t3.thread({project, title: "Thread A", messages: ["first"]});
  const b = await t3.thread({project, title: "Thread B", messages: ["first"]});
  const c = await t3.thread({project: other, title: "Thread C", messages: ["first"]});
  const origin = app.baseUrl ?? "";
  const environment = await runPromise(environmentId(origin));
  // Both revisions pin 0.21.41, whose RPC protocol the pool refuses. Use the
  // triage's 0.21.36 lease client on both sides; no stream or app behavior is mocked.
  const tool = `${T3_HOME}/tools/agent-device/0.21.41`;
  await mkdir(tool, {recursive:true});
  execFileSync("npm", ["install", "--prefix", tool, "--no-audit", "--no-fund", "agent-device@0.21.36"], {stdio:"pipe"});
  await writeFile(`${tool}/.install-complete`, "0.21.41\n");
  let opened: {hostId: string; deviceId: string} | undefined;
  await runPromise(Effect.gen(function*(){
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client["server.updateSettings"]({patch:{enableDeviceSupport:true, deviceOnboardingCompleted:true, simlockDeviceHostsEnabled:true, simlockDeviceHosts:[{kind:"simlock",id:"pool",label:"Device pool",maxLeases:2,maxLeaseMinutes:60,gatewayUrl:process.env.SIMLOCK_AGENT_DEVICE_URL!.replace(/\/v1\/agent-device\/?$/, ""),agentToken:process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN!}]}});
    yield* client["device.list"]({});
    opened = yield* client["device.open"]({threadId:ThreadId.make(a.threadId),hostId:"pool",deviceId:"simlock:android:Pixel 9",platform:"android"});
    for (const thread of [b,c]) yield* client["device.open"]({threadId:ThreadId.make(thread.threadId),hostId:opened.hostId,deviceId:opened.deviceId,platform:"android"});
  }).pipe(Effect.scoped));
  await t3.open(a);
  await browser.evaluate(async ({environment, threads, opened}) => {
    const module = await (new Function('return import("/src/previewMiniPlayerStore.ts")'))();
    for (const threadId of threads) module.usePreviewMiniPlayerStore.getState().open({environmentId:environment,threadId}, {kind:"device",hostId:opened.hostId,deviceId:opened.deviceId,platform:"android",name:"Pixel 9"});
  }, {environment,threads:[a.threadId,b.threadId,c.threadId],opened:opened!});
  const preview = browser.locator('[aria-label="Floating device preview"]');
  await preview.waitFor();
  await screen.getByText("Connecting video…",{exact:true}).waitFor({state:"hidden",timeout:120000});
  await browser.locator('[aria-label="Floating device preview"] canvas').waitFor({timeout:120000});
  await app.screenshot("live-before-switches");
  await browser.evaluate(() => {
    const w = window as any;
    w.streamProbe = {sockets:0, connecting:0};
    const Native = window.WebSocket;
    window.WebSocket = new Proxy(Native,{construct(target,args){if(String(args[0]).includes("/helper/ws")) w.streamProbe.sockets++; return Reflect.construct(target,args);}});
    new MutationObserver(() => {if(document.querySelector('[aria-label="Floating device preview"]')?.textContent?.includes("Connecting video")) w.streamProbe.connecting++;}).observe(document.body,{childList:true,subtree:true,characterData:true});
  });
  for (const title of ["Thread B", "Thread A", "Thread B", "Thread A", "Thread C", "Thread B"]) {
    await screen.getByRole("navigation","Threads").getByRole("button",title,{exact:false}).tap();
    await app.screenshot(`switch-to-${title.replace(" ","-")}`);
    await screen.getByText("Connecting video…",{exact:true}).waitFor({state:"hidden",timeout:120000});
  }
  await app.screenshot("live-after-switches");
  const probe = await browser.evaluate(() => (window as any).streamProbe);
  expect(probe, "Switching threads must keep the live video without new sockets or Connecting video").toEqual({sockets:0,connecting:0});
});
