import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Explicitly selecting the default scheduled-task model keeps its High effort", WEB,
async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1440, height: 1080 });
  const project = await t3.project("effort-demo");
  const earlier = await t3.thread({ project, title: "Earlier work", messages: ["Start"] });
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const file = (yield* Path.Path).join(T3_HOME, "userdata/settings.json");
    const settings = JSON.parse(yield* fs.readFileString(file));
    const capabilities = { optionDescriptors: [{ id: "reasoningEffort", label: "Reasoning effort", type: "select", options: [
      { id: "medium", label: "Medium", isDefault: true }, { id: "high", label: "High" }, { id: "low", label: "Low" }
    ] }] };
    settings.providerInstances.codex.enabled = true;
    settings.providerInstances.codex.config.binaryPath = "/usr/local/bin/codex";
    settings.providerInstances.codex.config.customModels = [
      { slug: "scheduled-reasoner", name: "Scheduled Reasoner", capabilities },
      { slug: "other-reasoner", name: "Other Reasoner", capabilities }
    ];
    settings.defaultModelSelection = { instanceId: "codex", model: "scheduled-reasoner", options: [{ id: "reasoningEffort", value: "high" }] };
    yield* fs.writeFileString(file, JSON.stringify(settings));
  }));
  await t3.open("/settings/threads");
  await screen.getByRole("button", "High", { exact: true }).waitFor();
  await app.screenshot("configured-default-effort-high");
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "New task").tap();
  await screen.getByRole("textbox", "Name").fill("Bound task uses thread model");
  await screen.getByRole("combobox", "Destination", { exact: true }).tap();
  await screen.getByRole("option", "One thread, continuing the conversation").tap();
  await screen.getByRole("combobox", "Destination thread").tap();
  await screen.getByRole("option", "Earlier work", { exact: false }).tap();
  await app.screenshot("bound-task-has-no-effort-editor");
  await screen.getByRole("button", "Cancel", { exact: true }).tap();
  const edit = async () => {
    await screen.getByRole("button", "Actions for Default High task").tap();
    await screen.getByRole("menuitem", "Edit", { exact: true }).tap();
  };
  const pickSame = async () => {
    await screen.getByRole("button", "Scheduled Reasoner", { exact: false }).tap();
    await browser.keyboard.type("Scheduled Reasoner");
    await screen.getByRole("option", "Scheduled Reasoner", { exact: false }).tap();
  };
  await screen.getByRole("button", "New task").tap();
  await screen.getByRole("textbox", "Name").fill("Default High task");
  await screen.getByRole("textbox", "Prompt").fill("Review the project using the configured High reasoning effort.");
  await pickSame();
  await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
  await screen.getByRole("option", "Use the project checkout", { exact: false }).tap();
  await screen.getByRole("switch", "Enabled", { exact: true }).tap();
  await app.screenshot("task-after-explicit-model-selection");
  await screen.getByRole("button", "Create task").tap();
  await edit();
  await app.screenshot("saved-task-reopened");
  await screen.getByRole("button", "Cancel", { exact: true }).tap();
  await screen.getByRole("button", "Actions for Default High task").tap();
  await screen.getByRole("menuitem", "Run now", { exact: true }).tap();
  const cli = makeState(T3_HOME).cli;
  const generated = async () => {
    const result = await runPromise(cli(["thread", "list", "--project", project, "--json"]));
    return JSON.parse(result.stdout).find((entry: { threadId: string }) => entry.threadId !== earlier.threadId);
  };
  let thread: { threadId: string } | undefined;
  await expect.poll(async () => { thread = await generated(); return Boolean(thread); }).toBe(true);
  await t3.open(thread!);
  await screen.getByRole("button", "Scheduled Reasoner", { exact: false }).waitFor();
  await screen.getByRole("button", "Stop generation", { exact: true }).tap();
  await screen.getByRole("button", "Resume thread", { exact: true }).waitFor();
  await app.screenshot("created-thread-actual-effort");
  await expect(screen.getByRole("button", "Scheduled Reasoner, High", { exact: true })).toBeVisible();

  await t3.open("/settings/scheduled-tasks");
  await edit();
  await screen.getByRole("button", "High", { exact: true }).tap();
  await screen.getByRole("menuitemradio", "Low", { exact: false }).tap();
  await screen.getByRole("button", "Save task").tap();
  await edit();
  await app.screenshot("changed-effort-reopened-low");
  await screen.getByRole("button", "Low", { exact: true }).tap();
  await screen.getByRole("menuitemradio", "High", { exact: false }).tap();
  await pickSame();
  await screen.getByRole("button", "Save task").tap();
  await edit();
  await app.screenshot("reselected-same-model-retains-high");
  await expect(screen.getByRole("button", "High", { exact: true })).toBeVisible();
  await screen.getByRole("button", "Scheduled Reasoner", { exact: false }).tap();
  await browser.keyboard.type("Other Reasoner");
  await screen.getByRole("option", "Other Reasoner", { exact: false }).tap();
  await app.screenshot("different-model-clears-high");
  await expect(screen.getByRole("button", "Medium", { exact: true })).toBeVisible();
  await screen.getByRole("button", "Cancel", { exact: true }).tap();

});
