import { expect } from "e2e";
import { writeFile } from "node:fs/promises";
import { test, WEB, runPromise, makeState } from "./t3.ts";
import { run } from "./shell.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

test("Data SVG keeps its internal url(%23g) gradient", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("SVG theme demo");
  const svg = '%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22400%22 height=%22800%22 viewBox=%220 0 400 800%22%3E%3Cdefs%3E%3ClinearGradient id=%22g%22 x2=%221%22 y2=%221%22%3E%3Cstop stop-color=%22%230b5563%22/%3E%3Cstop offset=%221%22 stop-color=%22%238a326e%22/%3E%3C/linearGradient%3E%3C/defs%3E%3Cpath fill=%22url(%23g)%22 d=%22M0 0h400v800H0z%22/%3E%3C/svg%3E';
  const file = `${T3_HOME}/url-repro.json`;
  await writeFile(file, JSON.stringify({name:"SVG Gradient",appearance:"dark",canvas:"#181820",accent:"#64d9e8",css:`[data-sidebar="sidebar"] { background-image: url('data:image/svg+xml,${svg}') !important; background-size: cover !important; }`}));
  const driver = `
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NetService from "@t3tools/shared/Net";
import * as EnvironmentAuth from "./src/auth/EnvironmentAuth.ts";
import * as ServerConfig from "./src/config.ts";
import { resolveCliAuthConfig } from "./src/cli/config.ts";
import { readLiveServerRuntimeState } from "./src/serverRuntimeState.ts";
import { mcpToolSession } from "./src/mcp/AcpMcpStdioBridge.ts";
import { readFileSync } from "node:fs";
const home = process.argv[1];
const theme = JSON.parse(readFileSync(process.argv[2], "utf8"));
const program = Effect.gen(function*() {
 const config = yield* resolveCliAuthConfig({baseDir:Option.some(home)}, Option.none(), {quietLogs:true});
 return yield* Effect.gen(function*() {
  const auth = yield* EnvironmentAuth.EnvironmentAuth;
  const issued = yield* Effect.acquireRelease(auth.issueMcpClientSession({label:"SVG proof",access:"full-access",peerLink:false,client:{deviceType:"bot"}}), s => auth.revokeSession(s.sessionId));
  const runtime = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
  const session = yield* mcpToolSession({endpoint:new URL("/mcp", Option.getOrThrow(runtime).origin).href,authorization:"Bearer " + issued.token,clientName:"svg-proof"});
  return yield* session.call("t3_theme_set", {themeId:"url-repro-agent",theme});
 }).pipe(Effect.scoped,Effect.provide(EnvironmentAuth.layerRuntime.pipe(Layer.provide(ServerConfig.layer(config)))));
}).pipe(Effect.provide([NodeServices.layer, NodeCrypto.layer, NetService.layer]));
try { console.log(JSON.stringify(await Effect.runPromise(program))); } catch(e) { console.error(String(e)); process.exit(1); }
`;
  const driverFile = `${APP_DIR}/apps/server/svg-proof-driver.mjs`;
  await writeFile(driverFile, driver.replace("process.argv[1]", "process.argv[2]").replace("readFileSync(process.argv[2]", "readFileSync(process.argv[3]"));
  const called = await runPromise(run(process.execPath, [driverFile, T3_HOME, file], {cwd:`${APP_DIR}/apps/server`}));
  const result = JSON.parse(called.stdout.trim().split("\n").at(-1)!);
  const resultText = result.content?.filter((c: {type:string}) => c.type === "text").map((c: {text:string}) => c.text).join("\n") ?? JSON.stringify(result);
  const thread = await t3.thread({ project, title: "Data SVG gradient", messages: [`Real t3_theme_set response for data SVG with fill=url(%23g):\n${resultText}`] });
  await runPromise(makeState(T3_HOME).cli(["theme", "set", file]));
  await t3.open(thread);
  await screen.getByRole("button", "Data SVG gradient", {exact:false}).first().waitFor({state:"visible"});
  await expect.poll(() => browser.evaluate(() => document.documentElement.dataset.themeId)).toBe("url-repro");
  await screen.getByRole("button", "Agent Real t3_theme_set response", {exact:false}).tap();
  await screen.getByText("Syncing messages...", {exact:false}).waitFor({state:"hidden"});
  await app.screenshot("svg-gradient-background");
  expect(result.isError ?? false).toBe(false);
  await expect.poll(() => browser.evaluate(() => getComputedStyle(document.querySelector('[data-sidebar="sidebar"]')!).backgroundImage)).toContain("linearGradient");
});
