/// <reference lib="dom" />
import * as FS from "node:fs/promises";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Uses the real OpenCode 1.19.6 binary; no provider responses are synthesized.
test("Every multi-file OpenCode apply_patch header is workspace-relative", WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width: 1600, height: 1000});
  const workspace = "/tmp/factory-pr-48601-evidence-2/workspace/ws";
  await FS.mkdir(workspace, {recursive: true});
  await FS.writeFile(`${workspace}/first.txt`, "alpha line\n");
  await FS.writeFile(`${workspace}/second.txt`, "beta line\n");
  await runPromise(run("git", ["init", "--quiet", "--initial-branch=main"], {cwd: workspace}));
  await runPromise(run("git", ["add", "first.txt", "second.txt"], {cwd: workspace}));
  await runPromise(run("git", ["-c", "user.name=Proof", "-c", "user.email=proof@example.invalid", "commit", "--quiet", "-m", "Initial files"], {cwd: workspace, allowExit: [0,1]}));
  const {cli} = makeState(T3_HOME);
  await runPromise(cli(["project", "add", workspace, "--title", "ws"]));
  const instanceId = ProviderInstanceId.make("opencode");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch: {defaultRuntimeMode: "full-access"}, providerInstanceMutation: {
      operation: "upsert", instanceId, instance: {driver: ProviderDriverKind.make("opencode"), enabled: true,
        displayName: "OpenCode", config: {binaryPath: "opencode1"},
        environment: [{name: "XDG_DATA_HOME", value: "/tmp/factory-pr-48601-evidence-2/opencode1-data", sensitive: false}]
      }
    }});
  }).pipe(Effect.scoped));
  const prompt = `Use exactly one apply_patch tool call to update both files. Do not use any other editing tool. Change first.txt from "alpha line" to "alpha updated" and second.txt from "beta line" to "beta updated". Use absolute paths ${workspace}/first.txt and ${workspace}/second.txt in the patch. Then reply only "Updated both files."`;
  const started = await runPromise(cli(["thread", "start", workspace, prompt, "--title", "Multi-file patch", "--provider", "opencode", "--model", "openai/gpt-5.6-luna", "--wait", "--json"]));
  const {threadId} = JSON.parse(started.stdout);
  await t3.open({threadId});
  const fold = screen.getByRole("button", /^Worked/);
  await fold.tap();
  await screen.getByText("Changed 2 files", {exact: true}).tap();
  await screen.getByRole("button", "ws/first.txt +1 more", {exact: true}).tap();
  await screen.getByRole("button", "Open diff", {exact: true}).tap();
  await screen.getByRole("button", "Maximize panel", {exact: true}).tap();
  await browser.locator("diffs-container").first().waitFor();
  const titles = () => browser.evaluate(() => Array.from(document.querySelectorAll("diffs-container"), h => h.shadowRoot?.querySelector("[data-title]")?.textContent ?? ""));
  await expect.poll(async () => (await titles()).length).toBe(2);
  await browser.evaluate(async () => {
    await document.fonts.ready;
    await Promise.all(Array.from(document.querySelectorAll("diffs-container"), host =>
      host.shadowRoot ? Array.from(host.shadowRoot.querySelectorAll("*"), element => element.getAnimations()).flat() : []
    ).flat().map(animation => animation.finished.catch(() => {})));
  });
  await app.screenshot("render-settling");
  await new Promise(resolve => setTimeout(resolve, 500));
  await app.screenshot("stability-check");
  // The proof brief requires two identical captures 500 ms apart before relying on a still.
  await new Promise(resolve => setTimeout(resolve, 500));
  await app.screenshot("multi-file-tool-diff");
  expect((await titles()).sort()).toEqual(["first.txt", "second.txt"]);
});
