import { readFileSync, watch, writeFileSync, existsSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];
const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();

test("BOM-prefixed t3.json honors sparse checkout and no submodules", WEB, async ({t3, app, browser, screen}) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const results: {label: string; sparse: boolean; excluded: boolean; submodule: boolean; submoduleAttempt: boolean; invalidConfig: boolean; thread: {threadId: string}; worktree: string}[] = [];
  for (const bom of [false, true]) {
    const label = bom ? "BOM configuration" : "No-BOM control";
    const project = await t3.project(bom ? "bomrepo" : "nobomrepo", {
      "t3.json": `${bom ? "\uFEFF" : ""}{"worktreeSparsePatternsPath":"sparse-patterns.txt","worktreeSubmodules":"none"}`,
      "sparse-patterns.txt": "/*\n!/excluded/\n",
      "keep/a.txt": "keep\n", "excluded/hidden.txt": "excluded\n",
    });
    const dep = `${project}/../dependency`;
    execFileSync("mkdir", ["-p", dep]);
    git(dep, "init", "--quiet", "--initial-branch=main");
    writeFileSync(`${dep}/contents.txt`, "dependency\n");
    git(dep, "add", "."); git(dep, ...author, "commit", "-qm", "Dependency");
    git(project, "-c", "protocol.file.allow=always", "submodule", "add", dep, "subm");
    git(project, ...author, "commit", "-qam", "Add submodule");
    // Seed a replay thread first so its advertised models are ready.
    await t3.thread({project, title: "Ready", messages: ["hello"]});
    const logPath = new URL("../.e2e/app.log", import.meta.url);
    const logOffset = readFileSync(logPath, "utf8").length;
    const started = await runPromise(makeState(T3_HOME).cli([
      "thread", "start", project, "Check this worktree", "--title", label,
      "--worktree", "main", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json",
    ]));
    const thread = JSON.parse(started.stdout) as {threadId: string};
    const worktree = await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl);
      const {thread: projection} = yield* client["orchestration.getThreadProjection"](thread as never);
      if (!projection.worktreePath) throw new Error("No worktree created");
      return projection.worktreePath;
    }).pipe(Effect.scoped));
    let sparse = false;
    try { sparse = git(worktree, "config", "--get", "core.sparseCheckout") === "true"; } catch {}
    const submodule = !git(worktree, "submodule", "status").startsWith("-");
    const logs = readFileSync(logPath, "utf8").slice(logOffset);
    const submoduleAttempt = logs.includes("initializing submodules recursively");
    const invalidConfig = logs.includes("t3.json is invalid");
    results.push({label, sparse, submoduleAttempt, invalidConfig, excluded: existsSync(`${worktree}/excluded/hidden.txt`), submodule, thread, worktree});
  }
  const bom = results[1]!;
  const report = results.map(r => `${r.label}\n  Sparse checkout enabled: ${r.sparse}\n  excluded/ checked out: ${r.excluded}\n  Submodule initialization attempted: ${r.submoduleAttempt}\n  Invalid t3.json warning: ${r.invalidConfig}\n`).join("\n");
  writeFileSync(`${bom.worktree}/bom-proof.txt`, "Measured worktrees created by T3 Code\n\n" + report);
  await t3.open(bom.thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await input.waitFor();
  await input.getAttribute("data-workspace-focus-default");
  // Wait for the terminal's input handlers, then show only synthetic fixture results.
  await input.focus();
  const printed = new Promise<void>((resolve) => {
    const watcher = watch(bom.worktree, (_event, name) => {
      if (name === "proof-ready") { watcher.close(); resolve(); }
    });
  });
  await browser.keyboard.type("PS1='' ; clear; cat bom-proof.txt; touch proof-ready");
  await browser.keyboard.press("Enter");
  await printed;
  // The terminal renders remotely after the shell writes the readiness marker.
  await new Promise(resolve => setTimeout(resolve, 1000));
  await app.screenshot("worktree-configuration-results");
  expect(results.map(({sparse, excluded, submoduleAttempt, invalidConfig}) => ({sparse, excluded, submoduleAttempt, invalidConfig}))).toEqual([
    {sparse: true, excluded: false, submoduleAttempt: false, invalidConfig: false},
    {sparse: true, excluded: false, submoduleAttempt: false, invalidConfig: false},
  ]);
});
