import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Failed nested repository restore identifies the missing checkout", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("shop", { ".gitignore": "inventory-api/\n" });
  const nested = `${project}/inventory-api`;
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.makeDirectory(nested)));
  const git = async (cwd: string, ...args: string[]) => (await runPromise(run("git", args, { cwd }))).stdout.trim();
  await git(nested, "init", "--initial-branch=main");
  await git(nested, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Initial inventory API");
  const { cli } = makeState(T3_HOME);
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(p => p.instanceId === "devReplay" && p.models.some(m => m.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const started = await runPromise(cli(["thread", "start", project, "Start", "--title", "Restore inventory checkout", "--worktree", "main", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout) as { threadId: string };
  const projection = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    return (yield* client["orchestration.getThreadProjection"](thread)).thread;
  }).pipe(Effect.scoped));
  if (!projection.worktreePath || !projection.branch) throw new Error("No thread workspace");
  const checkout = `${projection.worktreePath}/inventory-api`;
  await git(checkout, "rev-parse", "HEAD");
  await git(nested, "worktree", "remove", checkout);
  await git(nested, "switch", projection.branch);
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Continue in the project");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("Couldn't recreate thread workspace", { exact: true }).waitFor();
  await app.screenshot("failed-nested-checkout-restore");
  await expect(screen.getByText(`Could not recreate the worktree for branch '${projection.branch}' at ${checkout}.`, { exact: false }).first()).toBeVisible();
});
