import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NetService from "@t3tools/shared/Net";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import { readFile, writeFile } from "node:fs/promises";
import * as EnvironmentAuth from "../../apps/server/src/auth/EnvironmentAuth.ts";
import * as ServerConfig from "../../apps/server/src/config.ts";
import { resolveCliAuthConfig } from "../../apps/server/src/cli/config.ts";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("MCP project creation preserves actions on a folded install", WEB, async ({t3, app, browser, screen}) => {
  await t3.project("Existing project");
  // Reproduce the persisted state after the one-time project-settings fold.
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  await writeFile(settingsPath, JSON.stringify({...settings, projectSettingsFolded: true}));
  const scripts = [{id: "likec4-start", name: "LikeC4 podgląd", command: "npx -y likec4@latest start", icon: "play", runOnWorktreeCreate: false, async: true}];
  const {origin} = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const result = await runPromise(Effect.gen(function* () {
    const config = yield* resolveCliAuthConfig({baseDir: Option.some(T3_HOME)}, Option.none(), {quietLogs:true});
    return yield* Effect.gen(function* () {
      const auth = yield* EnvironmentAuth.EnvironmentAuth;
      const issued = yield* Effect.acquireRelease(auth.issueMcpClientSession({label:"Project action proof", access:"full-access", peerLink:false, client:{deviceType:"bot"}}), session => auth.revokeSession(session.sessionId));
      const session = yield* mcpToolSession({endpoint: `${origin}/mcp`, authorization:`Bearer ${issued.token}`, clientName:"project-action-proof"});
      const created: any = yield* session.call("t3_project_create", {title:"LikeC4 - experiments", workspaceRoot:`${T3_HOME}/workspaces/likec4-experiments`, createWorkspaceRootIfMissing:true, scripts});
      if (created.isError) throw new Error(JSON.stringify(created));
      const project = created.structuredContent;
      const read: any = yield* session.call("t3_project_read", {projectId:project.id});
      return {project, read:read.structuredContent};
    }).pipe(Effect.scoped, Effect.provide(EnvironmentAuth.layerRuntime.pipe(Layer.provide(ServerConfig.layer(config)), Layer.provide(Layer.succeed(References.MinimumLogLevel,"Error")))));
  }).pipe(Effect.provide([NetService.layer, NodeCrypto.layer])));
  const thread = await t3.thread({project:result.project.id, title:"Project action persistence", messages:["Start"]});
  await browser.setViewport({width:1280,height:800});
  await t3.open(thread);
  await screen.getByText("fixture turn complete", {exact:false}).waitFor();
  await app.screenshot("created-project-actions");
  expect(result.project.scripts, "MCP create returns the saved action").toEqual(scripts);
  expect(result.read.scripts, "MCP read returns the saved action").toEqual(scripts);
  await expect(screen.getByRole("button", "Run LikeC4 podgląd", {exact:true})).toBeVisible();
});
