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

const decode = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Struct({threadId: Schema.String})));
test("Cleanup tolerates an empty task folder after both checkouts were removed", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("app");
  const lib = `${project}/../lib`;
  const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, {cwd}));
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.makeDirectory(lib)));
  await git(lib, "init", "--initial-branch=main");
  await git(lib, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Initial commit");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const {projects} = yield* client["orchestration.getArchivedShellSnapshot"]({});
    const p = projects.find(p => p.workspaceRoot === project)!;
    yield* client["projects.mutate"]({type:"project.update", commandId:CommandId.make("scenario:add-lib"), projectId:p.id, trackedFolders:[{path:lib,name:"lib"}]});
  }).pipe(Effect.scoped));
  // Seed a replay thread first to await replay provider discovery.
  await t3.thread({project, title:"Ready", messages:["Hello"]});
  const {cli} = makeState(T3_HOME);
  const started = await runPromise(cli(["thread","start",project,"Hello","--title","Missing checkout","--worktree","main","--branch","cleanup-proof","--provider","devReplay","--model","multi-turn","--wait","--json"]));
  const thread = decode(started.stdout);
  const task = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const {thread: projection} = yield* client["orchestration.getThreadProjection"](thread);
    const {taskFolder} = yield* client["workspace.taskFolder"]({worktreePath:projection.worktreePath!});
    if (!taskFolder) throw new Error("No multi-repository task folder was created");
    return taskFolder;
  }).pipe(Effect.scoped));
  await t3.open(thread);
  for (const repo of task.repositories) await git(repo.repositoryPath, "worktree", "remove", "--force", repo.worktreePath);
  if (!task.repositories.some(repo => repo.worktreePath === task.projectPath)) await git(project, "worktree", "remove", "--force", task.projectPath);
  const empty = await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.readDirectory(task.root)));
  if (empty.length) throw new Error(`Task folder is not empty: ${empty}`);
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch:{storageCleanup:{worktreeOnMerge:true}}});
  }).pipe(Effect.scoped));
  await t3.open("/settings/maintenance");
  await screen.getByRole("button", "Delete now", {exact:true}).tap();
  await screen.getByRole("button", /^Last run/).tap();
  const report = browser.locator("#storage-cleanup-last-run");
  await report.waitFor();
  try {
    await expect(report).not.toContainText("NotFound");
    await expect(screen.getByText(/Cleanup failed on/)).not.toBeVisible();
  } finally { await app.screenshot("cleanup-after-missing-checkouts"); }
});
