import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { APP_DIR, MOBILE } from "../e2e.config.ts";
import { IOS, test } from "./t3-mobile.ts";
import { environmentId, runPromise } from "./t3.ts";

const image = (label: string, attributes: string, color: string, width: number) =>
  `![${label}](data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" ${attributes}><rect width="${width}" height="${color === 'red' ? 100 : 96}" fill="${color}"/></svg>`)})`;
const markdown = [
  'A: 2in with viewBox',
  image('A red', 'width="2in" height="96px" viewBox="0 0 100 100" preserveAspectRatio="none"', 'red', 100),
  'B: 2in without viewBox',
  image('B green', 'width="2in" height="96px"', 'green', 192),
  'C: 192px control',
  image('C blue', 'width="192px" height="96px"', 'blue', 192),
].join('\n\n');

test('SVG absolute lengths use the same frame as px', IOS, async ({t3, app, screen, device}) => {
  const fixture = `${APP_DIR}/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson`;
  const original = await readFile(fixture, 'utf8');
  const entries = original.trim().split('\n').map(line => JSON.parse(line));
  entries.find(entry => entry.label === 'first.assistant').frame.params.update.content.text = markdown;
  await writeFile(fixture, entries.map(entry => JSON.stringify(entry)).join('\n') + '\n');
  try {
    const project = await t3.project('SVG dimensions');
    const {threadId} = await t3.thread({project, title: 'SVG units', messages: ['Show the three SVG dimension examples.']});
    await t3.open();
    await screen.getByText('SVG units', {exact:false}).first().waitFor({timeout:120000});
    const environment = await runPromise(environmentId(`http://${MOBILE.host}:${MOBILE.serverPort}`));
    await device.openLink(`t3code-dev://threads/${environment}/${threadId}`, {app:'com.t3tools.t3code.dev'});
    await device.alert('accept').catch(() => {});
    await screen.getByRole('imagebutton', 'C blue').waitFor({timeout:120000});
    await app.screenshot('svg-absolute-unit-frames');
    const a = await screen.getByRole('imagebutton', 'A red').boundingBox();
    const b = await screen.getByRole('imagebutton', 'B green').boundingBox();
    const c = await screen.getByRole('imagebutton', 'C blue').boundingBox();
    expect({a: [a?.width, a?.height], b: [b?.width, b?.height], c: [c?.width, c?.height]}).toEqual({a:[192,96], b:[192,96], c:[192,96]});
  } finally { await writeFile(fixture, original); }
});
