import { expect } from "e2e";
import { writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { APP_DIR } from "../e2e.config.ts";
import { IOS, test } from "./t3-mobile.ts";

test("Chat line link has a visible native source marker", IOS, async ({ t3, app, screen, device }) => {
  const text = Array.from({length: 1150}, (_, i) => `${i+1}: ${i % 2 === 0 ? "A long paragraph with several words to wrap across the narrow phone screen. ".repeat(5) : "Short line."}`).join("\n");
  const frame = (frame: unknown) => ({type: "emit_inbound", frame});
  const transcript = [
    {type: "expect_outbound", frame: {kind: "request", method: "session/prompt", params: "<any>"}},
    frame({kind: "notification", method: "session/update", params: {sessionId: "replay", update: {sessionUpdate: "agent_message_chunk", content: {type: "text", text: "Line-link checks:\n\n[doc.md L645-647](file://<workspace>/doc.md#L645-L647)\n\n[doc.md L1135](file://<workspace>/doc.md#L1135)\n\n[doc.md L386-394](file://<workspace>/doc.md#L386-L394)\n\n[doc.md L73-81](file://<workspace>/doc.md#L73-L81)"}}}}),
    frame({kind: "response", method: "session/prompt", result: {stopReason: "end_turn"}}),
  ];
  writeFileSync(`${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`, transcript.map(x => JSON.stringify(x)).join("\n")+"\n");
  const project = await t3.project("line-link-demo", {"doc.md": text});
  await t3.thread({project, title: "Line-link proof", messages: ["Show the four document line links."], model: "command-output"});
  await device.setAppearance("dark");
  await t3.open();
  await screen.getByText("Line-link proof", {exact: false}).first().tap();
  await screen.getByText("doc.md", {exact: false}).first().tap();
  await screen.getByRole("button", "File actions").tap();
  await screen.getByText("Enable word wrap").tap();
  await screen.getByRole("button", "Back").tap();
  await screen.getByText("doc.md", {exact: false}).first().tap();
  await app.screenshot("wrap-L645");
  await screen.getByRole("button", "File actions").tap();
  await screen.getByText("Disable word wrap").tap();
  await screen.getByRole("button", "Back").tap();
  await screen.getByText("doc.md", {exact: false}).first().tap();
  await app.screenshot("nowrap-L645");
  const shot = await app.screenshot("nowrap-L645-marker");
  const count = Number(execFileSync("python3", ["-c", `from PIL import Image
import sys
im=Image.open(sys.argv[1]).convert("RGB")
w,h=im.size
# A visible selection bar differs from the neighboring sheet background.
n=sum(1 for y in range(int(h*.18),int(h*.85)) if max(im.getpixel((2,y)))-min(im.getpixel((2,y)))<35 and sum(im.getpixel((2,y)))/3 > 110 and sum(im.getpixel((20,y)))/3 < 90)
print(n)`, shot], {encoding:"utf8"}).trim());
  expect(count).toBeGreaterThan(15);
});
