import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProviderInstanceId, ProviderDriverKind } from "@t3tools/contracts";
import { readFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Enter in Save plan to workspace writes the plan and closes the dialog", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("migration-demo", {"README.md":"# Migration demo\n"});
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("claudeAgent"),
      instance: {driver: ProviderDriverKind.make("claudeAgent"), enabled: true, config: {}}
    }});
  }).pipe(Effect.scoped));
  const started = await runPromise(makeState(T3_HOME).cli([
    "thread", "start", project,
    "Call EnterPlanMode, write a plan file containing exactly '# Migration Plan\\n\\n1. Inspect the schema.\\n2. Apply the migration.\\n3. Verify the result.\\n', then call ExitPlanMode. Do not implement anything. Your final response must be only Plan ready. Do not mention any paths.",
    "--title", "Migration Plan", "--provider", "claudeAgent", "--model", "claude-haiku-5-5", "--wait", "--json"
  ], [0,2]));
  const {threadId} = JSON.parse(started.stdout);
  await t3.open({threadId});
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '[role="dialog"] code { visibility: hidden; }';
    document.head.appendChild(style);
    return null;
  });
  await screen.getByRole("button", "Plan actions").tap();
  await screen.getByRole("menuitem", "Save to workspace").tap();
  const dialog = screen.getByRole("dialog", "Save plan to workspace", {exact: true});
  await dialog.getByRole("textbox").fill("migration-plan.md");
  await app.screenshot("before-enter");
  await dialog.getByRole("textbox").press("Enter");
  try {
    await expect(dialog).toBeHidden();
    await expect.poll(async () => readFile(`${project}/migration-plan.md`, "utf8").catch(() => "")).toContain("# Migration Plan");
  } finally {
    await app.screenshot("after-enter");
  }
});
