import { execFileSync } from "node:child_process";
import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts";
import { environmentId, makeState, runPromise } from "./t3.ts";
import { IOS, test } from "./t3-mobile.ts";

test("SVG pixel dimensions accept a leading plus and decimal point", IOS, async ({t3, app, screen, device}) => {
  const svg = (width: string, color: string) => `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="80px" viewBox="0 0 100 100" preserveAspectRatio="none"><rect x="1" y="1" width="98" height="98" fill="${color}" stroke="black" stroke-width="2"/></svg>`;
  const project = await t3.project("SVG dimensions", {"plus.svg": svg("+200px", "red"), "dot.svg": svg(".5e2px", "blue"), "control.svg": svg("200px", "green")});
  const {cli} = makeState(MOBILE_T3_HOME, {T3CODE_PORT: String(MOBILE.serverPort)});
  const settingsPath = `${MOBILE_T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = {driver:"opencode", enabled:true, config:{binaryPath:`${process.env.HOME}/.local/bin/opencode`}};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const result = await runPromise(cli(["thread", "start", project, "Return exactly this Markdown, with no code fence or other text:\n\nPlus\n\n![plus](plus.svg)\n\nDot\n\n![dot](dot.svg)\n\nControl\n\n![control](control.svg)", "--title", "SVG pixel dimensions", "--provider", "opencode", "--model", "anthropic/claude-sonnet-4-6", "--wait", "--json"]));
  const {threadId} = JSON.parse(result.stdout);
  await t3.open();
  await screen.getByText("SVG pixel dimensions", {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.getByText("control", {exact:true}).first().waitFor({timeout:60000});
  const capture = await app.screenshot("svg-dimensions");
  const dimensions = JSON.parse(execFileSync("python3", ["-c", `
from PIL import Image
import json,sys
im=Image.open(sys.argv[1]).convert("RGB")
result={}
for name in ["red","blue"]:
 pts=[(x,y) for y in range(im.height) for x in range(im.width) if (lambda r,g,b:r>200 and g<40 and b<40 if name=="red" else b>200 and r<40 and g<40)(*im.getpixel((x,y)))]
 result[name]=[max(x for x,y in pts)-min(x for x,y in pts)+1,max(y for x,y in pts)-min(y for x,y in pts)+1]
print(json.dumps(result))
`, capture], {encoding:"utf8"}));
  // The stroke covers the outer 4% of the viewBox; compare the solid fill's aspect ratio.
  expect(dimensions.red[0] / dimensions.red[1]).toBeCloseTo(2.5, 1);
  expect(dimensions.blue[0] / dimensions.blue[1]).toBeCloseTo(0.625, 1);
});
