/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const commands = [
  "psql -f - <<'EOF'\nSELECT 1;\nEOF",
  "psql -c 'SELECT 2;' -f - <<'EOF'\nSELECT 1;\nEOF",
  "psql <<'EOF'\nSELECT 1;\nEOF",
  "psql --file=- <<'EOF'\nSELECT 1;\nEOF",
  "psql -Atf- <<'EOF'\nSELECT 1;\nEOF",
];

test("psql stdin file options highlight SQL in the expanded work log", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("SQL highlighting");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode.enabled = true;
  settings.providerInstances.opencode.config = { binaryPath: `${process.env.HOME}/.local/bin/opencode1` };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const prompt = "Run these five shell commands, each in its own bash tool call, exactly as written. Do not install anything or fix any errors. Even if psql is missing, run all five commands. Then reply with only 'SQL command checks complete'.\n\n" + commands.map(c => "```bash\n" + c + "\n```").join("\n\n");
  const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, prompt, "--title", "psql stdin SQL", "--provider", "opencode", "--model", "openai/gpt-6-luna", "--wait", "--json"]));
  const { threadId } = JSON.parse(started.stdout);
  await t3.open({ threadId });
  await screen.getByText("SQL command checks complete", { exact: true }).waitFor({ timeout: 60000 });
  await screen.getByRole("button", "Worked for", { exact: false }).tap();
  await screen.getByRole("button", /^Ran 5 commands/).tap();
  await screen.getByRole("button", "Toggle thread details panel", { exact: true }).tap();
  const colors: string[] = [];
  for (let i = 0; i < 5; i++) {
    const row = screen.getByRole("region", "Tool calls").getByRole("button", /^psql/).nth(i);
    await row.tap();
    await row.scrollIntoView();
    await expect.poll(() => browser.evaluate(() => [...document.querySelectorAll('[data-work-entry-id] span[style]')].filter(e => e.textContent === "SELECT").length)).toBeGreaterThan(0);
    await app.screenshot(["stdin-file", "inline-and-stdin", "stdin-control", "long-file-option", "bundled-file-option"][i]!);
    colors.push(await browser.evaluate(() => {
      const keywords = [...document.querySelectorAll('[data-work-entry-id] span[style]')].filter(e => e.textContent === "SELECT");
      return getComputedStyle(keywords[keywords.length - 1]!).color;
    }));
    await row.tap();
  }
  expect(colors).toEqual(Array(5).fill("rgb(177, 34, 81)"));
});
