import * as FS from "node:fs/promises";
import { expect } from "e2e";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as FileSystem from "effect/FileSystem";
import * as Auth from "../../apps/server/src/auth/EnvironmentAuth.ts";
import * as Config from "../../apps/server/src/config.ts";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB, runPromise } from "./t3.ts";

test("An agent can restore the stock T3 Code theme after publishing a custom theme", WEB,
  async ({ t3, app, screen, browser }) => {
    await browser.setViewport({ width: 1280, height: 1100 });
    await t3.project("Theme demonstration");
    await t3.open("/settings/appearance");
    const issued = await runPromise(Effect.gen(function* () {
      const auth = yield* Auth.EnvironmentAuth;
      const session = yield* auth.issueMcpClientSession({ label: "Theme demonstration", access: "full-access", peerLink: false, client: { deviceType: "bot" } });
      const config = yield* Config.ServerConfig;
      const fs = yield* FileSystem.FileSystem;
      const runtime = JSON.parse(yield* fs.readFileString(config.serverRuntimeStatePath));
      return { token: session.token, origin: runtime.origin };
    }).pipe(Effect.provide(Auth.layerRuntime.pipe(Layer.provideMerge(Config.layerTest(APP_DIR, T3_HOME)))), Effect.provide(NodeCrypto.layer)));
    const call = (name: string, args: Record<string, unknown>) => runPromise(Effect.gen(function* () {
      const session = yield* mcpToolSession({ endpoint: `${issued.origin}/mcp`, authorization: `Bearer ${issued.token}`, clientName: "theme-proof" });
      return yield* session.call(name, args);
    }).pipe(Effect.scoped));
    const initial = await call("t3_theme_read", {});
    await call("t3_theme_set", { themeId: "agent-look", appearance: "light", theme: { version: 1, name: "Agent Look", appearance: "light", colors: { canvas: "#ffe4ed", accent: "#be185d" } } });
    await screen.getByRole("button", "Use Agent Look theme").waitFor({ state: "visible" });
    await app.screenshot("custom-theme");
    const reset = await call("t3_theme_set", { themeId: "t3-code" });
    const read = await call("t3_theme_read", {});
    const summary = (result: any) => result.structuredContent ?? result;
    const cleanRead = (result: any) => {
      const { current, builtIn, published, guide } = result.structuredContent;
      return { current, builtIn, published, guide };
    };
    if (process.env.THEME_PROOF_OUTPUT) {
      const folder = await FS.mkdtemp(`${process.env.THEME_PROOF_OUTPUT}/run-`);
      await FS.writeFile(`${folder}/theme-transcript.json`, JSON.stringify({ initial: cleanRead(initial), reset: summary(reset), final: cleanRead(read) }, null, 2));
    }
    await app.screenshot("restore-stock-theme");
    expect(reset).not.toHaveProperty("isError", true);
    await expect(screen.getByRole("button", "Use T3 Code light mode", { exact: true })).toHaveAttribute("aria-pressed", "true");
    expect((read as { structuredContent: { current: string } }).structuredContent.current).toBe("");
    expect((read as { structuredContent: { guide: string } }).structuredContent.guide).toContain("t3-code");
  });
