import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const commands = ["psql -c 'select 1'", "psql -Atc 'select 1'", "mysql -Ne 'select 1'", "mariadb -sNe'select 1'", "psql -Atf query.sql <<'EOF'\nselect 1;\nEOF"];

test("Bundled SQL options highlight inline SQL and ignore file-mode stdin", WEB, async ({t3, app, screen, browser}) => {
  const path = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await fs.readFile(path, "utf8");
  const update = (value: unknown) => ({type:"emit_inbound", frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:value}}});
  const frames: unknown[] = [{type:"transcript_start",provider:"acpRegistry",protocol:"acp.ndjson-jsonrpc",version:"1",scenario:"sql_commands"},{type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}}];
  commands.forEach((command, i) => {
    frames.push(update({sessionUpdate:"tool_call",toolCallId:`sql-${i}`,kind:"execute",title:command,status:"in_progress",rawInput:{command}}));
    frames.push({...update({sessionUpdate:"tool_call_update",toolCallId:`sql-${i}`,status:"completed",rawOutput:"1\n"}),afterMs:300});
  });
  frames.push(update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"SQL commands complete."}}),{type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  await fs.writeFile(path, frames.map(f=>JSON.stringify(f)).join("\n")+"\n");
  try {
    const project = await t3.project("SQL demo");
    const thread = await t3.thread({project,title:"SQL commands",messages:["Run the SQL commands"],model:"command-output"});
    await t3.open(thread);
    await screen.getByText("SQL commands complete.").waitFor();
    await screen.getByRole("button","Worked for",{exact:false}).tap();
    await screen.getByRole("button","Ran 5 commands",{exact:false}).tap();
    for (const prefix of ["psql -c", "psql -Atc", "mysql -Ne", "mariadb -sNe", "psql -Atf"]) {
      await screen.getByRole("button",prefix,{exact:false}).first().tap();
    }
    await browser.locator('span[style*="color"]').first().waitFor();
    await app.screenshot("sql-commands-expanded");
    const colors = await browser.evaluate(() => Array.from(document.querySelectorAll('span[style*="color"]')).filter(e=>e.textContent === "select").map(e=>getComputedStyle(e).color));
    console.log("SQL keyword colors", JSON.stringify(colors));
    await expect(colors).toEqual([
      "rgb(177, 34, 81)", "rgb(177, 34, 81)", "rgb(177, 34, 81)", "rgb(177, 34, 81)",
      "rgb(16, 106, 43)",
    ]);
  } finally { await fs.writeFile(path, original); }
});
