import { expect } from "e2e";
import { mkdir, rename, writeFile, lstat, readFile } from "node:fs/promises";
import * as Effect from "effect/Effect";
import { CommandId, ProjectSnapshot } from "@t3tools/contracts";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
import { run } from "./shell.ts";

test("Adding a deep repository keeps sibling files in every intermediate folder", WEB, async ({t3, app, browser, screen}) => {
  const shop = await t3.project("shop", {"api/README.md":"API repository\n", "tools/run.sh":"echo tools\n", "tools/libs/notes.md":"Sibling notes must remain visible\n"});
  await rename(`${shop}/.git`, `${shop}/api/.git`);
  const git = (cwd: string, args: string[]) => runPromise(run("git", args, {cwd}));
  await git(`${shop}/api`, ["add", "--all"]);
  await git(`${shop}/api`, ["-c","user.name=Scenario","-c","user.email=scenario@example.invalid","commit","-qm","API repository"]);
  const updateFolders = async (deep: boolean) => runPromise(Effect.gen(function* () {
    const issued = yield* makeState(T3_HOME).cli(["auth","session","issue","--token-only"]);
    const { projects } = yield* HttpClient.execute(HttpClientRequest.get(`${app.baseUrl}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim()))).pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
    const project = projects.find(p => p.workspaceRoot === shop)!;
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client["projects.mutate"]({type:"project.update", commandId:CommandId.make(crypto.randomUUID()), projectId:project.id, trackedFolders:[{name:"api",path:`${shop}/api`}, ...(deep ? [{name:"deep",path:`${shop}/tools/libs/deep`}] : [])]});
  }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer)));
  await updateFolders(false);
  const started = await runPromise(makeState(T3_HOME).cli(["thread","start",shop,"hello","--title","Deep repository","--worktree","main","--branch","t3/hello","--provider","devReplay","--model","multi-turn","--wait","--json"]));
  const thread = JSON.parse(started.stdout) as {threadId:string};
  await t3.open(thread);
  await screen.getByText("hello", {exact:true}).first().waitFor();
  const deep = `${shop}/tools/libs/deep`;
  await mkdir(deep, {recursive:true});
  await writeFile(`${deep}/README.md`, "Deep repository\n");
  await git(deep,["init","-q","--initial-branch=main"]);
  await git(deep,["add","--all"]);
  await git(deep,["-c","user.name=Scenario","-c","user.email=scenario@example.invalid","commit","-qm","Deep repository"]);
  await updateFolders(true);
  await t3.open(thread);
  const other = screen.getByRole("button","Other repositories...", {exact:true});
  await screen.getByText("hello", {exact:true}).first().waitFor();
  const details = screen.getByRole("button","Toggle thread details panel",{exact:true});
  await details.waitFor();
  if ((await details.getAttribute("aria-pressed")) === "false") await details.tap();
  await other.tap();
  await screen.getByRole("menuitem","deep",{exact:true}).tap();
  await screen.getByRole("group","Repository deep",{exact:true}).waitFor();
  await screen.getByRole("button","Toggle terminal drawer",{exact:true}).tap();
  const terminal = screen.getByLabel("Terminal input");
  const listing = await git(`${shop}/api`, ["worktree","list","--porcelain"]);
  const checkout = listing.stdout.split("\n\n").find(block => block.includes("branch refs/heads/t3/hello"))!.split("\n")[0]!.slice(9);
  const root = checkout.slice(0, -4);
  const ready = `${checkout}/terminal-ready`;
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("printf ready > api/terminal-ready");
    await browser.keyboard.press("Enter");
    return readFile(ready,"utf8").catch(()=>"");
  }, {timeout:30_000}).toBe("ready");
  const report = `${checkout}/inspection.txt`;
  await browser.keyboard.type(`PS1='$ '; clear; printf 'Thread folder after adding deep repository\\n\\n'; printf 'tools/:\\n'; ls tools; printf '\\ntools/libs/:\\n'; ls tools/libs; printf '\\nSibling notes: '; if test -L tools/libs/notes.md; then echo 'PRESENT (link)'; cat tools/libs/notes.md; else echo MISSING; fi; printf '\\nDeep repository branch: '; git -C tools/libs/deep branch --show-current; printf done > api/inspection.txt`);
  await browser.keyboard.press("Enter");
  await expect.poll(() => readFile(report,"utf8").catch(()=>""),{timeout:15_000}).not.toBe("");
  await app.screenshot("sibling-files-after-adding-deep");
  const sibling = await lstat(`${root}/tools/libs/notes.md`).catch(()=>null);
  expect(sibling?.isSymbolicLink() ?? false).toBe(true);
});
