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

test("Question answer context labels stay readable", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("claudeAgent"),
      instance: { driver: ProviderDriverKind.make("claudeAgent"), enabled: true, config: {} }
    }});
  }).pipe(Effect.scoped));
  const started = await runPromise(makeState(T3_HOME).cli([
    "thread", "start", project,
    "Use AskUserQuestion now to ask: What should I fix? Give options A and B. Wait for my answer. Do not use any other tools.",
    "--title", "Context chip answer", "--provider", "claudeAgent", "--model", "claude-haiku-5-5", "--wait", "--json"
  ], [0, 2]));
  const thread = JSON.parse(started.stdout) as { threadId: string };
  await writeFile(`${project}/<context>.md`, "This line needs fixing.\n");
  await t3.open(thread);
  await browser.locator('[data-pending-user-input-toggle]').waitFor({ timeout: 60000 });
  await screen.getByRole("textbox").fill("Please fix this line");
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("button", "Expand <context>.md").tap();
  const linePoint = await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const line = host.shadowRoot?.querySelector('[data-column-number="1"]');
      if (line) { const r = line.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }
    }
    throw new Error("No diff line gutter");
  });
  await browser.mouse.move(linePoint.x, linePoint.y);
  const buttonPoint = await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const button = host.shadowRoot?.querySelector<HTMLButtonElement>('[data-gutter-utility-slot] button');
      if (button) { const r = button.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }
    }
    throw new Error("No comment button");
  });
  await browser.mouse.move(buttonPoint.x, buttonPoint.y);
  await browser.mouse.down();
  await browser.mouse.up();
  await screen.getByRole("textbox", /^Comment on lines/).fill("Please fix this line");
  await screen.getByRole("button", "Comment", { exact: true }).tap();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Submit", { exact: true }).tap();
  await browser.locator('[data-pending-user-input-toggle]').waitFor({ state: "hidden" });
  await app.screenshot("collapsed-answer");
  await screen.getByText(/\[Review comment:/).first().tap();
  await app.screenshot("expanded-answer");
  await expect(screen.getByText("[Review comment: <context>.md L1]", { exact: false }).first()).toBeVisible();
  await expect(screen.getByText(/t3_context version=/)).toBeHidden();
});
