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

test("Later checkouts inherit a repository group's custom name in headers and drafts", WEB, async ({ t3, app, browser, screen }) => {
  const capture = async (label: string) => {
    await browser.evaluate(async () => {
      await document.fonts.ready;
      await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
    });
    await app.screenshot(label);
  };
  const source = await t3.project("fixture-source", { "subfolder/README.md": "Subfolder project\n" });
  const cli = (args: string[]) => runPromise(makeState(T3_HOME).cli(args));
  const git = (args: string[], cwd = source) => runPromise(run("git", args, { cwd }));
  let count = 0;
  const checkout = async (name: string, origin: string) => {
    const parent = `${source}/case-${++count}`;
    await mkdir(parent);
    const path = `${parent}/${name}`;
    await git(["clone", "--quiet", source, path]);
    await git(["remote", "set-url", "origin", origin], path);
    await cli(["project", "add", path]);
    return path;
  };
  const origin = "https://example.invalid/scenario/demo.git";
  const first = await checkout("demo", origin);
  await cli(["project", "rename", first, "demo-renamed"]);
  const later = await checkout("demo", origin);
  const thread = await t3.thread({ project: later, title: "Later checkout", messages: ["first"] });
  await t3.open(thread);
  const breadcrumb = screen.getByRole("button", /^New thread in /).first();
  await breadcrumb.waitFor();
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await browser.locator("[data-composer-sync-status]").waitFor({ state: "hidden" });
  await capture("renamed-later-checkout-thread");
  await expect.soft(breadcrumb).toHaveAttribute("aria-label", "New thread in demo-renamed");
  await breadcrumb.tap();
  const picker = browser.locator("[data-draft-project-trigger]");
  await picker.waitFor();
  await capture("renamed-later-checkout-draft");
  await expect.soft(picker).toHaveText("demo-renamed");
  await picker.hover();
  await browser.locator('[data-slot="tooltip-popup"]').waitFor();
  await capture("renamed-later-checkout-tooltip");
  await expect.soft(browser.locator('[data-slot="tooltip-popup"]')).toHaveText("demo-renamed");
  await picker.tap();
  await capture("renamed-group-picker");
  await browser.keyboard.press("Escape");

  const plainOrigin = "https://example.invalid/scenario/plain.git";
  await checkout("plain-first", plainOrigin);
  const plain = await checkout("plain-later", plainOrigin);
  const subfolder = `${later}/subfolder`;
  await cli(["project", "add", subfolder]);
  const conflictOrigin = "https://example.invalid/scenario/conflict.git";
  const conflictA = await checkout("conflict-first", conflictOrigin);
  await cli(["project", "rename", conflictA, "Custom A"]);
  const conflictB = await checkout("conflict-second", conflictOrigin);
  await cli(["project", "rename", conflictB, "Custom B"]);
  const conflict = await checkout("conflict-later", conflictOrigin);
  for (const [project, title] of [[plain, "Unrenamed group"], [subfolder, "Repository subfolder"], [conflict, "Conflicting renames"]]) {
    const control = await t3.thread({ project, title, messages: ["first"] });
    await t3.open(control);
    await screen.getByRole("button", /^New thread in /).first().waitFor();
    await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await browser.locator("[data-composer-sync-status]").waitFor({ state: "hidden" });
    await capture(title.toLowerCase().replaceAll(" ", "-"));
    await screen.getByRole("button", /^New thread in /).first().tap();
    await picker.waitFor();
    await capture(`${title.toLowerCase().replaceAll(" ", "-")}-draft`);
  }
  await t3.open("/settings/general");
  await screen.getByRole("switch", "Project grouping", { exact: true }).tap();
  await t3.open(thread);
  await breadcrumb.waitFor();
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await browser.locator("[data-composer-sync-status]").waitFor({ state: "hidden" });
  await capture("separate-grouping-thread");
  await breadcrumb.tap();
  await picker.waitFor();
  await capture("separate-grouping-draft");
  await t3.open("/settings/general");
  await screen.getByRole("switch", "Project grouping", { exact: true }).tap();
  await t3.open(thread);
  await breadcrumb.tap();
  await picker.waitFor();
  await runPromise(Effect.gen(function* () {
    const issued = yield* makeState(T3_HOME).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 });
    for (const project of projects) yield* client.projects.mutate({ headers, payload: {
      type: "project.update", commandId: CommandId.make(`archive-${project.id}`), projectId: project.id, archived: true,
    } });
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  await picker.waitFor({ state: "hidden" });
  const addProject = browser.locator('main button').filter({ hasText: /^demo(?:-renamed)?$/ });
  await addProject.waitFor();
  await capture("archived-groups-no-picker-add-project-label");
  await expect.soft(addProject).toHaveText("demo-renamed");
});
