import { createServer } from "node:http";
import sharp from "sharp";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Simlock open reports the daemon explanation", WEB, async ({ t3, app, screen }) => {
  const gateway = createServer((req, res) => {
    if (req.url === "/v1/catalog") {
      res.setHeader("content-type", "application/json");
      res.end(JSON.stringify({ platforms: [{ platform: "android", modelRuntimes: { "Pixel 9": ["36"] } }] }));
    } else if (req.url === "/v1/identity") {
      res.setHeader("content-type", "application/json");
      res.end(JSON.stringify({ name: "Scenario", role: "agent" }));
    } else { res.writeHead(404, { "content-type": "text/plain" }); res.end("404 Not Found"); }
  });
  await new Promise<void>((resolve) => gateway.listen(0, "127.0.0.1", resolve));
  try {
    const address = gateway.address();
    if (!address || typeof address === "string") throw new Error("Gateway did not listen");
    const project = await t3.project("device-demo");
    await t3.thread({ project, title: "Simlock open failure", messages: ["Ready"] });
    await t3.open();
    await screen.getByText("Simlock open failure", { exact: true }).first().waitFor({ state: "visible" });
    await app.open("/settings/labs");
    await screen.getByRole("switch", "Simlock device hosts").tap();
    await app.open("/settings/devices");
    await screen.getByRole("switch", "Device hub", { exact: true }).tap();
    await screen.getByRole("button", "Add source").tap();
    await screen.getByRole("menuitem", "Simlock pool (alpha)").tap();
    await screen.getByRole("textbox", "Name", { exact: true }).fill("Demo gateway");
    await screen.getByRole("textbox", "Gateway URL").fill(`http://127.0.0.1:${address.port}`);
    await screen.getByRole("textbox", "Agent token", { exact: true }).fill("synthetic-demo-token");
    await screen.getByRole("button", "Save host").tap();
    await screen.getByRole("button", "Save host").waitFor({ state: "hidden" });
    await app.open("/");
    await screen.getByRole("button", "Simlock open failure, Done, device-demo", { exact: true }).tap();
    await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
    await screen.getByRole("button", "Device M", { exact: true }).tap();
    await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
    await app.screenshot("before-start");
    await screen.getByRole("button", "Start Pixel 9", { exact: true }).tap();
    await screen.getByText("failed to boot:", { exact: false }).first().waitFor({ state: "visible" });
    let previous = await sharp(await app.screenshot("settled-first")).raw().toBuffer();
    let stable = false;
    for (let attempt = 0; attempt < 8; attempt++) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const current = await sharp(await app.screenshot("simlock-open-failure")).raw().toBuffer();
      if (previous.equals(current)) { stable = true; break; }
      previous = current;
    }
    if (!stable) throw new Error("Error view did not settle");
    await expect(screen.getByText("Invalid daemon response", { exact: false }).first()).toBeVisible();
    await expect(screen.getByText("The daemon answered: 404 Not Found", { exact: false }).first()).toBeVisible();
  } finally { await new Promise<void>((resolve) => gateway.close(() => resolve())); }
});
