import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";

import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const SettingsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));
const decodeSettings = Schema.decodeEffect(SettingsJson);
const encodeSettings = Schema.encodeEffect(SettingsJson);

const threadRuntimeSettings = Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  const settingsPath = (yield* Path.Path).join(T3_HOME, "userdata/settings.json");
  const original = yield* fs.readFileString(settingsPath);
  const settings = yield* decodeSettings(original);
  return {
    supervise: fs.writeFileString(
      settingsPath,
      yield* encodeSettings({ ...settings, defaultRuntimeMode: "approval-required" }),
    ),
    restore: fs.writeFileString(settingsPath, original),
  };
});

test(
  "Editing a queued message into /btw does not save it to the main conversation",
  WEB,
  async ({ t3, app, screen }) => {
    const settings = await runPromise(threadRuntimeSettings);
    try {
      await runPromise(settings.supervise);
      const project = await t3.project("Queued edit demo");
      const thread = await t3.thread({
        project,
        title: "Queued side-chat question",
        messages: ["write the probe file again"],
        model: "approval",
      });
      const { cli } = makeState(T3_HOME);
      await runPromise(cli(["thread", "send", thread.threadId, "Can you explain this part?"]));
      await t3.open(thread);
      await screen.getByRole("button", "Edit queued message").tap();
      const composer = screen.getByRole("textbox");
      await composer.fill("/btw Can you explain this part?");
      await screen.getByRole("button", "Update queued message").tap();
      await app.screenshot("after-update");
      const sendNow = screen.getByRole("button", "Send now", { exact: true });
      if (await sendNow.isVisible()) await sendNow.tap();
      await expect(screen.getByText("Queued message not updated", { exact: true })).toBeVisible();
      await expect(composer).toContainText("/btw Can you explain this part?");
      await app.screenshot("draft-preserved");
    } finally {
      await runPromise(settings.restore);
    }
  },
);
