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

const prompt = `Exercise the actual T3 html_preview and html_render MCP tools. Do not edit files or implement a validator. Call html_preview separately for each of these four exact html strings, then html_render separately for the same four strings (title each case and height 200):
1. <main style="min-height:100vh">Example</main>
2. <main style="min-height:+100vh">Example</main>
3. <main style="min-height:1e2vh">Example</main>
4. <style>main{min-height:1e+2vh}</style><main>Example</main>
Make all eight calls, even if some fail. Do not change the HTML after errors. Find the tools with tool_search if needed. Finally report a compact markdown table with one row per tool and case: actual ACCEPTED or REJECTED and contentHeight for successful previews. Keep the table compact: put the shared error message once below the table, with the different matched unit strings listed. Count actual outcomes and finish with exactly RESULT: N rejected, M accepted (substitute actual counts). Do not make any other tool calls after reporting. This is a tool validation experiment; report errors as outcomes, do not fix them.`;

test("Both HTML tools reject signed and scientific viewport heights", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("viewport-validation");
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const original = await fs.readFile(settingsPath, "utf8");
  const settings = JSON.parse(original);
  settings.providerInstances.opencode = { driver: "opencode", displayName: "OpenCode", enabled: true, config: {} };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  try {
    const { cli } = makeState(T3_HOME);
    const started = await runPromise(cli(["thread", "start", project, prompt, "--title", "Viewport height validation", "--provider", "opencode", "--model", "anthropic/claude-sonnet-5-5", "--wait", "--json"]));
    const { threadId } = JSON.parse(started.stdout);
    await t3.open({ threadId });
    await screen.getByText("RESULT:", { exact: false }).last().waitFor({ timeout: 60000 });
    await screen.getByText("Syncing messages…", { exact: true }).waitFor({ state: "hidden" });
    await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 1500)));
    await screen.getByText("Syncing messages…", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("html-tool-outcomes");
    await expect(screen.getByText("RESULT: 8 rejected, 0 accepted", { exact: false }).last()).toBeVisible();
  } finally {
    await fs.writeFile(settingsPath, original);
  }
});
