import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const prompt = `Create a temporary PNG named inspected.png in the current project using Python standard library (zlib and struct) or another available image utility. Make it a 480x240 blue image with a yellow rectangle so it is recognizable. Inspect that PNG using your native view_image tool, then delete inspected.png using a shell command in this same turn. Do not return a markdown image or create any other image. After deletion verify that inspected.png no longer exists. End your final response with the exact sentence: "Inspected image deleted."`;

test("An image inspected by real Codex survives source deletion and thread reload", WEB,
 async ({t3, app, screen, browser}) => {
  const project = await t3.project("image-preview-demo");
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.codex = { driver: "codex", enabled: true, config: { binaryPath: "/usr/local/bin/codex" } };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  await runPromise(Effect.gen(function*() {
   const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
   yield* client.subscribeServerConfig({}).pipe(Stream.filter(event =>
    (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [])
     .some(provider => provider.instanceId === "codex" && provider.enabled)), Stream.runHead);
  }).pipe(Effect.scoped));
  const {cli} = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, prompt, "--title", "Image survives cleanup", "--provider", "codex", "--model", "gpt-6.1-sol", "--option", "reasoningEffort=low", "--json"]));
  const {threadId} = JSON.parse(started.stdout);
  await t3.open({threadId});
  await screen.getByText("Inspected image deleted.", {exact:true}).waitFor({timeout:180000});
  await fs.access(path.join(project,"inspected.png")).then(() => {throw new Error("Source PNG was not deleted");}, () => {});
  await screen.getByRole("button", "Worked for", {exact:false}).tap();
  await browser.locator("[data-image-gallery]").first().waitFor({timeout:30000});
  await app.screenshot("after-cleanup");
  await t3.open({threadId});
  // Reopen the document to discard any previously loaded image pixels and signed URL.
  await browser.evaluate(() => location.reload());
  await screen.getByText("Inspected image deleted.", {exact:true}).waitFor({timeout:60000});
  await screen.getByRole("button", "Worked for", {exact:false}).tap();
  await browser.locator("[data-image-gallery]").first().waitFor({timeout:30000});
  await screen.getByText("Syncing messages...", {exact:false}).waitFor({state:"hidden",timeout:30000});
  await app.screenshot("after-reload");
  await expect(screen.getByRole("button", "Preview inspected.png")).toBeVisible();
  await screen.getByRole("button", "Preview inspected.png").tap();
  await app.screenshot("image-gallery");
  await expect(browser.locator('[role="dialog"] img').first()).toBeVisible();
 });
