import { chmod, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { execFileSync } from "node:child_process";
import { ProviderInstanceId } from "@t3tools/contracts";
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";

test("A renamed worktree branch does not report that it stayed at its old name", WEB, async ({ t3, app, screen }) => {
  const helper = createServer((_request, response) => {
    response.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({
      choices: [{ finish_reason: "stop", message: { content: JSON.stringify({ branch: "add-default-macros", title: "Add default macros" }) } }],
    }));
  });
  await new Promise<void>((resolve) => helper.listen(0, "127.0.0.1", resolve));
  try {
    const address = helper.address();
    if (!address || typeof address === "string") throw new Error("No helper address");
    const instanceId = ProviderInstanceId.make("scenario-branch-name");
    await runPromise(Effect.scoped(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: {
        textGenerators: { [instanceId]: { kind: "openaiCompatible", baseUrl: `http://127.0.0.1:${address.port}`, apiKey: "", enabled: true } },
        textGenerationModelSelection: { instanceId, model: "recorded-branch-name" },
      } });
    })));
    const project = await t3.project("macro-demo");
    await writeFile(`${project}/.git/config.lock`, "");
    await chmod(`${project}/.git/config.lock`, 0o444);
    const result = await runPromise(makeState(T3_HOME).cli([
      "thread", "start", "--provider", "devReplay", "--model", "showcase",
      "--worktree", "main", project, "Add default macros", "--wait", "--json",
    ], [0, 2]));
    console.log("Actual Git branches after thread launch:", execFileSync("git", ["branch", "--list"], { cwd: project, encoding: "utf8" }));
    const thread = JSON.parse(result.stdout);
    await t3.open({ threadId: thread.threadId });
    await screen.getByText("Add default macros", { exact: true }).first().waitFor({ state: "visible" });
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await screen.getByText("clamp(12, 0, 10);", { exact: false }).first().waitFor();
    await app.screenshot("branch-rename-result");
    await expect(screen.getByText(/Could not rename the worktree branch, so it stays/)).toBeHidden();
  } finally {
    await new Promise<void>((resolve, reject) => helper.close((error) => error ? reject(error) : resolve()));
  }
});
