import * as fs from "node:fs/promises";
import { DatabaseSync } from "node:sqlite";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Bash keeps NBSP inside an assignment in the live command label", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("bash-words");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.codex = {driver:"codex", enabled:true, config:{binaryPath:"/usr/local/bin/codex"}};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const {cli} = makeState(T3_HOME);
  const prompt = "Run exactly this command once using your shell tool, preserving the literal U+00A0 between one and two. Do not normalize whitespace, do not inspect files, do not run any other commands: bash -c 'env X=one\u00a0two sleep 40'";
  let threadId;
  for(let attempt=0;attempt<8 && !threadId;attempt++) {
    const started = await runPromise(cli(["thread","start",project,prompt,"--title","Bash NBSP command","--provider","codex","--model","gpt-6.1-sol","--json"],[0,1]));
    if(started.stdout.includes('threadId')) threadId=JSON.parse(started.stdout).threadId;
  }
  if(!threadId) throw new Error("Codex thread did not start");
  await t3.open({threadId});
  await screen.getByText(/^Running /).first().waitFor({timeout:120000});
  const db = new DatabaseSync(`${T3_HOME}/userdata/statev2.sqlite`, {readOnly:true});
  const rows = db.prepare("SELECT payload_json FROM orchestration_events WHERE payload_json LIKE '%env X=%' UNION ALL SELECT payload_json FROM orchestration_v2_events WHERE payload_json LIKE '%env X=%'").all();
  const commands = new Set<string>();
  const visit = (x: unknown) => {
    if (typeof x === "string" && x.includes("env X=") && !x.includes("Run exactly")) commands.add(x);
    else if (Array.isArray(x)) x.forEach(visit);
    else if (x && typeof x === "object") Object.values(x).forEach(visit);
  };
  rows.forEach(row => visit(JSON.parse(String(row.payload_json))));
  db.close();
  const verified = [...commands].filter(command => command.includes("one\u00a0two"));
  if (!verified.length) throw new Error(`The real provider did not preserve literal NBSP in the recorded tool event; rows=${rows.length}; commands=${JSON.stringify([...commands])}`);
  console.log("COMMAND_BYTE_PROOF",JSON.stringify(verified.map(command=>({command,hex:Buffer.from(command).toString("hex")}))));
  await app.screenshot("live-bash-command");
  await expect(screen.getByText("Running sleep",{exact:true})).toBeVisible();
});
