/// <reference lib="dom" />
import { DatabaseSync } from "node:sqlite";
import { writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A four-space backtick line keeps attached terminal context in an open fence", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({project, title: "Open fence terminal context", messages: ["Start"], model: "default"});
  await t3.open("/settings/chat");
  await screen.getByRole("switch", "Rich text composer").tap();
  await t3.open(thread);
  const toggle = screen.getByRole("button", "Toggle terminal drawer");
  await toggle.tap();
  const input = browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]');
  await input.waitFor();
  await input.focus();
  await browser.keyboard.type("PS1=''; printf '\\033[2J\\033[HBUILD FAILED\\n'\n");
  await toggle.tap();
  const editor = browser.locator('[data-testid="composer-editor"][contenteditable="true"]');
  await editor.tap();
  await browser.keyboard.type("```");
  await editor.press("Shift+Enter");
  await toggle.tap();
  await input.focus();
  await browser.keyboard.press("Control+Shift+A");
  await browser.locator("canvas.cursor-text").secondaryTap();
  await screen.getByText("Add to chat", {exact:true}).tap();
  await toggle.tap();
  await editor.getByRole("button", /^Terminal excerpt,/).tap();
  await screen.getByLabel("Captured terminal output", {exact: true}).waitFor();
  await app.screenshot("attached-output-before-four-space-line");
  await browser.keyboard.press("Escape");
  await editor.tap();
  await editor.press("Control+End");
  await editor.press("Shift+Enter");
  await browser.keyboard.type("    ```");
  await app.screenshot("four-space-fence-terminal-context");
  await screen.getByRole("button", "Submit message", {exact: true}).tap();
  await screen.getByRole("button", "Submit message", {exact: true}).waitFor();
  const db = new DatabaseSync(`${T3_HOME}/userdata/statev2.sqlite`, {readOnly: true});
  const row = db.prepare("SELECT payload_json FROM orchestration_v2_projection_messages WHERE thread_id = ? AND role = 'user' ORDER BY created_at DESC LIMIT 1").get(thread.threadId);
  db.close();
  if (!row) throw new Error("Sent user message missing");
  const message = JSON.parse(String(row.payload_json));
  const {projectComposerContextForProvider} = await import(pathToFileURL(`${APP_DIR}/packages/shared/src/composerContextReferences.ts`).href);
  const projected = projectComposerContextForProvider({text: message.text, records: message.context?.records ?? []});
  const sha = execFileSync("git", ["rev-parse", "HEAD"], {cwd: APP_DIR, encoding: "utf8"}).trim();
  const side = sha === "9b746515a8cafcacf7244c6d7dd6e8c3ea94ed82" ? "head" : "base";
  writeFileSync(new URL(`../.e2e/prove/${side}-provider-projection.json`, import.meta.url), JSON.stringify({sha, text: message.text, context: message.context ?? null, projected}, null, 2));
  await expect(projected).toContain("1 | BUILD FAILED");
});
