/// <reference lib="dom" />
// The DOM lib types the function this scenario runs in the page.
import { expect } from "e2e";
import { readFileSync, watch } from "node:fs";
import { fileURLToPath } from "node:url";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";

import { APP_DIR, MOBILE_T3_HOME as T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise } from "./t3.ts";
import { test, IOS } from "./t3-mobile.ts";

const decodeRuntime = Schema.decodeUnknownEffect(
  Schema.fromJsonString(Schema.Struct({ pid: Schema.Int })),
);

/** The scenario's own server: the pid its T3 home records, running from the app checkout. */
const scenarioServerPid = Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  const runtime = yield* Effect.firstSuccessOf(
    ["userdata", "dev"].map((dir) =>
      fs.readFileString(path.join(T3_HOME, dir, "server-runtime.json")),
    ),
  );
  const { pid } = yield* decodeRuntime(runtime);
  const cwd = yield* fs.readLink(`/proc/${pid}/cwd`);
  if (!cwd.startsWith(path.resolve(APP_DIR))) {
    return yield* Effect.die(new Error(`pid ${pid} runs in ${cwd}, not ${APP_DIR}`));
  }
  return pid;
});

/**
 * Linux only: leaves the server no free file descriptor, so node-pty's forkpty(3) fails as it does when a
 * host runs out. Returns the restore; only this process's soft limit changes.
 */
const exhaustFileDescriptors = Effect.fn("scenario.exhaustFileDescriptors")(function* (
  pid: number,
) {
  const limits = yield* run("prlimit", [
    `--pid=${pid}`,
    "--nofile",
    "--raw",
    "--noheadings",
    "--output=SOFT,HARD",
  ]);
  const [soft = "", hard = ""] = limits.stdout.trim().split(/\s+/);
  yield* run("prlimit", [`--pid=${pid}`, `--nofile=0:${hard}`]);
  return run("prlimit", [`--pid=${pid}`, `--nofile=${soft}:${hard}`]);
});

test("An iOS terminal operator sees a real shell startup failure", IOS, async ({ t3, app, screen }) => {
  const project = await t3.project("demo");
  await t3.thread({ project, title: "Shell startup", messages: ["hello"] });
  await t3.open();
  await screen.getByText("Shell startup", { exact: false }).first().tap();
  await screen.getByRole("button", "Terminal").tap();
  await expect(screen.getByRole("button", /^Open new terminal/)).toBeVisible();
  const pid = await runPromise(scenarioServerPid);
  const logPath = fileURLToPath(new URL("../.e2e/mobile-app.log", import.meta.url));
  const initialLogLength = readFileSync(logPath, "utf8").length;
  let stopWatching = () => {};
  const failedStartup = new Promise<void>((resolve, reject) => {
    const timer = setTimeout(() => { stopWatching(); reject(new Error("No real PTY startup failure was logged")); }, 20_000);
    const watcher = watch(logPath, () => {
      if (readFileSync(logPath, "utf8").slice(initialLogLength).includes("failed to start terminal")) {
        clearTimeout(timer); watcher.close(); resolve();
      }
    });
    stopWatching = () => { clearTimeout(timer); watcher.close(); };
  });
  const restore = await runPromise(exhaustFileDescriptors(pid));
  try {
    await screen.getByRole("button", /^Open new terminal/).tap();
    await failedStartup;
  } finally {
    stopWatching();
    await runPromise(restore);
  }
  await expect(screen.getByRole("button", /^Terminal options/)).toBeVisible();
  await app.screenshot("mobile-startup-failure");
  await expect(screen.getByText("Failed to spawn PTY process", { exact: false })).toBeVisible();
});
