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("Send now on the only queued slash command does something", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("demo");
  const settings = await runPromise(threadRuntimeSettings);
  try {
    await runPromise(settings.supervise);
    const waiting = await t3.thread({
      project,
      title: "Waiting work",
      messages: ["Change the file"],
      model: "approval",
    });
    await runPromise(
      makeState(T3_HOME).cli([
        "thread",
        "send",
        waiting.threadId,
        "/ultrathink about how to set this up",
      ]),
    );
    await t3.open(waiting);
    await expect(screen.getByRole("button", "Edit queued message")).toBeVisible();
    await app.screenshot("queued-before-click");
    const sendNow = screen.getByRole("button", "Send now");
    await sendNow.hover();
    await app.screenshot("send-now-tooltip");
    for (let click = 0; click < 3; click += 1) {
      await sendNow.click();
    }
    await app.screenshot("after-three-clicks");
    // Reported bug: the command is still queued, Send now is still offered, and nothing explains why.
    await expect(screen.getByRole("button", "Send now")).not.toBeVisible();
  } finally {
    await runPromise(settings.restore);
  }
});
