import * as fs from "node:fs/promises";
import { CommandId, EnvironmentHttpApi } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient } from "effect/http";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Rebuilding a multi-repository workspace reruns synchronous project setup", WEB,
async ({ t3, app, browser, screen }) => {
  const project = `${T3_HOME}/workspaces/rebuild-demo`;
  await fs.mkdir(`${project}/api`, { recursive: true });
  await fs.writeFile(`${project}/README.md`, "Demo workspace\n");
  await fs.writeFile(`${project}/.gitignore`, "/api/\n");
  await fs.writeFile(`${project}/api/a.txt`, "API checkout\n");
  for (const cwd of [project, `${project}/api`]) {
    for (const args of [["init", "--quiet", "--initial-branch=main"], ["add", "--all"],
      ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial commit"]]) {
      await runPromise(run("git", args, { cwd }));
    }
  }
  const { cli } = makeState(T3_HOME);
  const added = await runPromise(cli(["project", "add", project]));
  const projectId = /Added project (\S+) /.exec(added.stdout)?.[1];
  if (!projectId || !added.stdout.includes("1 other folder")) throw new Error(`Nested repository not discovered: ${added.stdout}`);
  t3.trackProject(projectId);
  await runPromise(Effect.gen(function* () {
    const issued = yield* cli(["auth", "session", "issue", "--token-only"]);
    const headers = { authorization: `Bearer ${issued.stdout.trim()}` };
    const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: app.baseUrl });
    const { projects } = yield* client.projects.snapshot({ headers });
    const entry = projects.find(p => p.id === projectId)!;
    yield* client.projects.mutate({ headers, payload: {
      type: "project.update", commandId: CommandId.make(`setup-${entry.id}`), projectId: entry.id,
      scripts: [{ id: "prepare", name: "Prepare", command: "touch setup-ready", icon: "play", runOnWorktreeCreate: true, async: false }],
    }});
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  const started = await runPromise(cli(["thread", "start", project, "Start", "--title", "Rebuild workspace", "--worktree", "main", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  const shown = JSON.parse((await runPromise(cli(["thread", "show", thread.threadId, "--json"]))).stdout);
  const workspace = shown.thread.worktreePath;
  if (!workspace || !(await fs.stat(`${workspace}/setup-ready`)).isFile()) throw new Error("Creation setup did not run");
  await fs.rm(workspace, { recursive: true });
  await runPromise(cli(["thread", "send", thread.threadId, "Continue here", "--wait"]));
  await t3.open(thread);
  await screen.getByText("Continue here", { exact: true }).last().waitFor();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]');
  await input.waitFor();
  await input.focus();
  await browser.keyboard.type("export PS1='$ '; printf '\\033[2J\\033[H'; printf 'After deleting workspace and completing follow-up turn\\n'; printf 'Root checkout: '; test -f README.md && echo restored; printf 'API checkout: '; test -f api/a.txt && test -f api/.git && echo restored; if test -f setup-ready; then echo 'Project setup: setup-ready PRESENT'; else echo 'Project setup: setup-ready MISSING'; fi; touch .evidence-printed\n");
  // Wait for the terminal command itself to finish, then let its prompt render.
  await expect.poll(async () => fs.stat(`${workspace}/.evidence-printed`).then(() => true, () => false)).toBe(true);
  await app.screenshot("rebuilt-workspace-setup");
  expect(await fs.stat(`${workspace}/setup-ready`).then(() => true, () => false)).toBe(true);
});
