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

const command = String.raw`printf '\033[42m PASS \033[0m\n\033[1;37;41m FAIL \033[0m\n\033[7m\033[1m\033[32m PASS \033[0m\n\033[30;42m PASS \033[0m\n\033[100m SKIP \033[0m\n'`;
const output = "\x1b[42m PASS \x1b[0m\n\x1b[1;37;41m FAIL \x1b[0m\n\x1b[7m\x1b[1m\x1b[32m PASS \x1b[0m\n\x1b[30;42m PASS \x1b[0m\n\x1b[100m SKIP \x1b[0m\n";

test("Command output badges meet the existing 3:1 contrast target", WEB, async ({ t3, app, screen, browser }) => {
  // Replay the exact command result through the real ACP adapter and orchestration.
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const update = (value: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "badge-replay", update: value } } });
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    update({ sessionUpdate: "tool_call", toolCallId: "badges", kind: "execute", title: command, status: "in_progress", rawInput: { command } }),
    update({ sessionUpdate: "tool_call_update", toolCallId: "badges", status: "completed", content: [{ type: "content", content: { type: "text", text: output } }] }),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "done" } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  let thread;
  try {
    await writeFile(fixture, frames.map(frame => JSON.stringify(frame)).join("\n") + "\n");
    const project = await t3.project("badge-contrast");
    thread = await t3.thread({ project, title: "ANSI command badge contrast", messages: ["Run the ANSI badge command and reply done."], model: "showcase" });
  } finally {
    await writeFile(fixture, original);
  }
  await browser.addInitScript(() => {
    if (!localStorage.getItem("t3code:theme")) localStorage.setItem("t3code:theme", "dark");
    localStorage.setItem("t3code:theme-follow-system", "false");
  });
  await t3.open(thread);
  await screen.getByRole("button", /Worked for/).tap();
  await screen.getByRole("button", /printf/).tap();
  await screen.getByText("SKIP", { exact: true }).last().waitFor({ state: "visible" });
  const dark = await browser.evaluate(() => {
    const luminance = (rgb: string) => {
      const channels = rgb.match(/[\d.]+/g)!.slice(0,3).map(Number).map(n => n / 255).map(n => n <= .04045 ? n / 12.92 : ((n + .055) / 1.055) ** 2.4);
      return channels[0] * .2126 + channels[1] * .7152 + channels[2] * .0722;
    };
    return [...document.querySelectorAll("span")].filter(el => ["PASS", "FAIL", "SKIP"].includes(el.textContent!.trim()) && !el.querySelector("span") && (el as HTMLElement).style.backgroundColor !== "").map(el => {
      const style = getComputedStyle(el);
      const fg = luminance(style.color), bg = luminance(style.backgroundColor);
      return { text: el.textContent!.trim(), foreground: style.color, background: style.backgroundColor, contrast: (Math.max(fg,bg)+.05)/(Math.min(fg,bg)+.05) };
    });
  });
  console.log("Dark rendered badge contrast", JSON.stringify(dark));
  await app.screenshot("dark-command-badges");
  await browser.evaluate(() => { localStorage.setItem("t3code:theme", "light"); });
  await browser.reload();
  const fold = screen.getByRole("button", /Worked for/);
  await fold.waitFor({ state: "visible" });
  if (await fold.getAttribute("aria-expanded") !== "true") await fold.tap();
  const row = screen.getByRole("button", /printf/);
  if (await row.getAttribute("aria-expanded") !== "true") await row.tap();
  await screen.getByText("SKIP", { exact: true }).last().waitFor({ state: "visible" });
  await app.screenshot("light-command-badges");
  expect(dark.length).toBe(5);
  for (const badge of dark) expect(badge.contrast).toBeGreaterThanOrEqual(3);
});
