import { expect } from "e2e";
import { readFile, watch } from "node:fs/promises";
import { makeState, runPromise } from "./t3.ts";
import { MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts";
import { IOS, test } from "./t3-mobile.ts";

test("A launched command sees the measured terminal grid", IOS, async ({ t3, app, screen, device }) => {
  const project = await t3.project("terminal-grid");
  const { cli } = makeState(MOBILE_T3_HOME, { T3CODE_PORT: String(MOBILE.serverPort) });
  const issued = await runPromise(cli(["auth", "session", "issue", "--token-only", "--ttl", "15m"]));
  const headers = { authorization: `Bearer ${issued.stdout.trim()}`, "content-type": "application/json" };
  const origin = `http://127.0.0.1:${MOBILE.serverPort}`;
  const snapshot = await (await fetch(`${origin}/api/projects`, { headers })).json();
  const projectId = snapshot.projects.find((item: { workspaceRoot: string }) => item.workspaceRoot === project).id;
  const updated = await fetch(`${origin}/api/projects/mutate`, { method: "POST", headers, body: JSON.stringify({
    type: "project.update", commandId: crypto.randomUUID(), projectId,
    scripts: [{ id: "measure-grid", name: "Measure grid", command: "PS1='$ '; clear; printf 'Launch grid: '; stty size | tee launch-grid.txt; sleep 2; printf 'Settled grid: '; stty size | tee settled-grid.txt", icon: "play", runOnWorktreeCreate: false }],
  }) });
  if (!updated.ok) throw new Error(`Project action setup failed: ${updated.status}`);
  await t3.thread({ project, title: "Terminal grid proof", messages: ["hello"] });
  await t3.open();
  await screen.getByText("Terminal grid proof", { exact: false }).first().tap();
  await device.setOrientation("landscape-left");
  await screen.getByRole("button", "Terminal").tap();
  await screen.getByText("Measure grid", { exact: false }).first().tap();
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), 30000);
  try {
    for await (const event of watch(project, { signal: controller.signal })) {
      if (event.filename === "settled-grid.txt") {
        const value = await readFile(`${project}/settled-grid.txt`, "utf8");
        if (value.trim()) break;
      }
    }
  } finally { clearTimeout(timeout); }
  await app.screenshot("terminal-grid");
  const launch = (await readFile(`${project}/launch-grid.txt`, "utf8")).trim();
  const settled = (await readFile(`${project}/settled-grid.txt`, "utf8")).trim();
  expect(launch).toBe(settled);
});
