import { expect } from "e2e";

import { MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise } from "./t3.ts";
import { IOS, test } from "./t3-mobile.ts";

test(
  "Opening a thread on iOS soon after its checkout failed shows the worktree setup failure",
  IOS,
  async ({ t3, app, screen }) => {
    const project = await t3.project("failed-checkout", {
      "t3.json": JSON.stringify({ worktreeSparsePatternsPath: "missing-patterns.txt" }),
    });
    // A local simulator keeps the last run's pairing.
    await app.clearState().catch(() => {});
    // Load the app before the checkout fails: the server keeps a failed setup for 30 seconds.
    await t3.open();
    await t3.open();
    await screen.getByText("No threads yet", { exact: false }).first().waitFor({
      timeout: 240_000,
    });
    const primary = makeState(MOBILE_T3_HOME, { T3CODE_PORT: String(MOBILE.serverPort) });
    await runPromise(
      primary.cli(
        [
          "thread",
          "start",
          project,
          "Review the demo",
          "--worktree",
          "main",
          "--provider",
          "devReplay",
          "--model",
          "showcase",
          "--wait",
          "--json",
        ],
        [1],
      ),
    );
    await screen.getByText("Review the demo", { exact: false }).first().tap({ timeout: 10_000 });
    await screen.getByRole("textbox", "Ask anything").waitFor({ timeout: 30_000 });
    await app.screenshot("checkout-failure-on-open");
    await expect(screen.getByText("Worktree setup failed", { exact: false }).first()).toBeVisible();
  },
);
