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(
  "A reply-only unsaved queued edit is recovered when its run starts",
  WEB,
  async ({ t3, app, screen }) => {
    const settings = await runPromise(threadRuntimeSettings);
    try {
      await runPromise(settings.supervise);
      const project = await t3.project("demo");
      const thread = await t3.thread({ project, title: "Waiting work", messages: ["Change the file"], model: "approval" });
      await t3.open(thread);
      await screen.getByRole("button", "Approve", { exact: true }).tap();
      await screen.getByRole("button", "Reply to this response").first().waitFor();
      const { cli } = makeState(T3_HOME);
      await runPromise(cli(["thread", "send", thread.threadId, "Change it again", "--wait", "--json"], [0, 2]));
      await runPromise(cli(["thread", "send", thread.threadId, "Queued follow-up"]));
      await screen.getByRole("button", "Edit queued message").tap();
      await screen.getByRole("button", "Reply to this response").first().tap();
      const composer = screen.getByRole("textbox");
      await composer.press("Enter");
      await screen.getByRole("button", "Edit queued message").tap();
      await screen.getByRole("button", "Cancel reply").tap();
      await app.screenshot("unsaved-reply-removal");
      await screen.getByRole("button", "Approve", { exact: true }).tap();
      await screen.getByRole("button", "Cancel editing queued message").waitFor({ state: "hidden" });
      await app.screenshot("recovered-reply-only-edit");
      await expect(composer).toContainText("Queued follow-up");
      await expect(screen.getByText("was kept in the composer", { exact: false })).toBeVisible();
      await expect(screen.getByRole("button", "Cancel reply")).not.toBeVisible();
    } finally { await runPromise(settings.restore); }
  },
);
