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

const commands = [
  "duckdb -s 'SELECT 42 AS answer'",
  "duckdb -s 'select 1' -s 'select 2'",
  "duckdb -c 'SELECT 42 AS answer'",
  "duckdb -newline -s -s 'SELECT 7 AS separator_check'",
];

test("DuckDB -s operands get SQL colors, including repeated scripts, while -newline consumes its separator", WEB, async ({t3,app,screen,browser}) => {
  const project = await t3.project("duckdb-demo");
  await fs.copyFile(process.env.DUCKDB_PROOF_BINARY!, path.join(APP_DIR,"node_modules/.bin/duckdb"));
  await fs.chmod(path.join(APP_DIR,"node_modules/.bin/duckdb"),0o755);
  const settingsPath = path.join(T3_HOME,"userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath,"utf8"));
  settings.providerInstances.claudeAgent = {driver:"claudeAgent",enabled:true,config:{binaryPath:"/usr/local/bin/claude"}};
  settings.defaultRuntimeMode = "full-access";
  await fs.writeFile(settingsPath,JSON.stringify(settings));
  const {cli} = makeState(T3_HOME);
  const prompt = "Run each of these exact commands as a separate Bash tool call, unchanged, in this order. Do not combine them. Do not use other tools or commands. After all four, reply exactly DUCKDB_COMPLETE.\n" + commands.join("\n");
  const launched = await runPromise(cli(["thread","start",project,prompt,"--title","DuckDB inline SQL","--provider","claudeAgent","--model","claude-haiku-5-5","--wait","--json"]));
  const {threadId} = JSON.parse(launched.stdout);
  await t3.open({threadId});
  await screen.getByText("DUCKDB_COMPLETE",{exact:false}).last().waitFor({timeout:120000});
  await screen.getByRole("button","Worked for",{exact:false}).tap();
  await screen.getByRole("button","Ran 4 commands",{exact:false}).tap();
  const colors = [];
  const labels = ["single-s-script", "repeated-s-scripts", "c-control", "newline-separator"];
  for (const [index, command] of commands.entries()) {
    const row = screen.getByRole("button",command,{exact:false}).first();
    await row.tap();
    await browser.evaluate(async (command) => {
      await new Promise<void>((resolve) => {
        const ready = () => [...document.querySelectorAll("div")].some(el => el.textContent === command && el.querySelector("span[style]"));
        if (ready()) return resolve();
        const observer = new MutationObserver(() => {
          if (ready()) { observer.disconnect(); resolve(); }
        });
        observer.observe(document.body, {childList:true, subtree:true, attributes:true});
      });
      const block = [...document.querySelectorAll("div")].find(el => el.textContent === command && el.querySelector("span[style]"));
      block?.scrollIntoView({block:"center"});
    },command);
    await app.screenshot(labels[index]!);
    colors.push(await browser.evaluate((command) => {
    const block = [...document.querySelectorAll("div")].find(el => el.textContent === command && el.querySelector("span[style]"));
    return block ? [...block.querySelectorAll<HTMLElement>("span[style]")].map(el=>({text:el.textContent,color:getComputedStyle(el).color})) : [];
    }, command));
    await row.tap();
  }
  console.log("DUCKDB_COLORS",JSON.stringify(colors));
  const sqlColors = colors.map(tokens => tokens.filter(token => /SELECT|select|42|\b1\b|\b2\b|\b7\b/.test(token.text??"")).map(token=>token.color));
  expect(sqlColors[0].length).toBeGreaterThan(1);
  expect(new Set(sqlColors[0]).size).toBeGreaterThan(1);
  expect(new Set(sqlColors[1]).size).toBeGreaterThan(1);
  expect(colors[1].some(token=>token.text === "select")).toBe(true);
  expect(colors[1].filter(token=>token.text === "select").length).toBe(2);
  expect(sqlColors[0]).toEqual(sqlColors[2]);
  expect(colors[3].some(token=>token.text === "SELECT")).toBe(true);
});
