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

test("Diff reads the repository whose directory ends in a space", WEB, async ({ t3, app, screen }) => {
  const initialProject = await t3.project("review-demo");
  const project = await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const outside = yield* fs.makeTempDirectory({ directory: "/tmp/factory-pr-47804-evidence-1", prefix: "review-demo-" });
    yield* fs.copy(initialProject, `${outside}/parent`);
    const { stdout } = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const headers = { authorization: `Bearer ${stdout.trim()}` };
    const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: app.baseUrl });
    const { projects } = yield* client.projects.snapshot({ headers });
    const entry = projects.find(({ workspaceRoot }) => workspaceRoot === initialProject);
    if (!entry) throw new Error("Seed project missing");
    yield* client.projects.mutate({ headers, payload: { type: "project.update", commandId: CommandId.make(`move-${entry.id}`), projectId: entry.id, workspaceRoot: `${outside}/parent` } });
    return `${outside}/parent`;
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  const repository = `${project}/repo `;
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.rename(`${project}/.git`, `${project}/../parent-git-metadata`);
    yield* fs.makeDirectory(repository);
    const git = (...args: string[]) => run("git", args, { cwd: repository });
    yield* git("init", "--initial-branch=main");
    yield* fs.writeFileString(`${repository}/file.txt`, "old\n");
    yield* git("add", "file.txt");
    yield* git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Initial file");
    yield* fs.writeFileString(`${repository}/file.txt`, "new\n");
  }));
  await runPromise(Effect.gen(function* () {
    const { stdout } = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const headers = { authorization: `Bearer ${stdout.trim()}` };
    const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: app.baseUrl });
    const { projects } = yield* client.projects.snapshot({ headers });
    const entry = projects.find(({ workspaceRoot }) => workspaceRoot === project);
    if (!entry) throw new Error("Seed project missing");
    yield* client.projects.mutate({ headers, payload: { type: "project.update", commandId: CommandId.make(`track-${entry.id}`), projectId: entry.id, trackFolders: [{ path: repository, name: "repo" }] } });
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  const thread = await t3.thread({ project, title: "Review literal repository path", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor({ timeout: 60_000 });
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("button", /^Repository:/).tap();
  await screen.getByRole("menuitemradio", "repo", { exact: true }).tap();
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitemradio", "Uncommitted", { exact: true }).tap();
  await app.screenshot("literal-repository-uncommitted-diff");
  await expect(screen.getByRole("button", /^(Expand|Collapse) file\.txt$/)).toBeVisible();
});
