// @effect-diagnostics nodeBuiltinImport:off -- Uses the repository's ACP fixture from the reported reproduction.
import * as FS from "node:fs/promises";
import { watch } from "node:fs";
import * as Path from "node:path";
import { pathToFileURL } from "node:url";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("ACP preserves choices with an empty value and title", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Form choices");
  const outcomes: Record<string, unknown> = {};
  const cases = [
    { id: "single", title: "Single select — empty title", property: "mode", field: { type: "string", oneOf: [{ const: "", title: "" }, { const: "fast", title: "Fast" }] }, expected: { mode: "" } },
    { id: "control", title: "Control — Default title", property: "mode", field: { type: "string", oneOf: [{ const: "", title: "Default" }, { const: "fast", title: "Fast" }] }, expected: { mode: "" } },
    { id: "multi", title: "Multi select — empty title", property: "tags", field: { type: "array", items: { anyOf: [{ const: "", title: "" }, { const: "fast", title: "Fast" }] } }, expected: { tags: [""] } },
  ];
  for (const item of cases) {
    const responseLog = Path.join(project, `${item.id}-response.json`);
    const script = Path.join(project, `${item.id}-fixture.mjs`);
    const schema = { type: "object", required: [item.property], properties: { [item.property]: item.field } };
    await FS.writeFile(script, `process.env.T3_ACP_EMIT_ELICITATION = "1";\nprocess.env.T3_ACP_ELICITATION_SCHEMA = ${JSON.stringify(JSON.stringify(schema))};\nprocess.env.T3_ACP_ELICITATION_RESPONSE_LOG_PATH = ${JSON.stringify(responseLog)};\nawait import(${JSON.stringify(pathToFileURL(Path.join(APP_DIR, "apps/server/scripts/acp-mock-agent.ts")).href)});\n`);
    const instanceId = ProviderInstanceId.make(`elicit-${item.id}`);
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
        operation: "upsert", instanceId, instance: {
          driver: ProviderDriverKind.make("acpRegistry"), displayName: `Elicit Fixture ${item.id}`, enabled: true,
          config: { source: "local", commandPath: process.execPath, commandArgs: [script] },
        },
      } });
    }).pipe(Effect.scoped));
    const { cli } = makeState(T3_HOME);
    const started = await runPromise(cli(["thread", "start", project, "Configure this run", "--title", item.title,
      "--provider", instanceId, "--model", "default", "--wait", "--json"], [0, 2]));
    const run = JSON.parse(started.stdout);
    await t3.open({ threadId: run.threadId });
    await screen.getByText("Configure this run", { exact: true }).waitFor({ timeout: 60000 });
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden", timeout: 60000 });
    if (started.exitCode === 2 || run.status === "waiting") {
      const options = browser.locator("[data-chat-composer-form] button[aria-pressed]");
      const option = options.first();
      await expect(option).toBeVisible();
      await expect(option).toHaveText(item.id === "control" ? /^Default\s*1$/ : /^""\s*1$/);
      await expect(options.nth(1)).toHaveText(/^Fast\s*2$/);
      await app.screenshot(`${item.id}-choices`);
      const received = new Promise<void>((resolve, reject) => {
        const timer = setTimeout(() => { watcher.close(); reject(new Error("No elicitation response received")); }, 15000);
        const watcher = watch(project, async (_event, filename) => {
          if (filename !== Path.basename(responseLog)) return;
          try { if ((await FS.readFile(responseLog, "utf8")).trim()) { clearTimeout(timer); watcher.close(); resolve(); } } catch {}
        });
      });
      await option.tap();
      if (item.id === "multi") {
        await app.screenshot("multi-empty-selected");
        await screen.getByRole("button", "Submit", { exact: true }).tap();
      }
      await received;
      await browser.locator("[data-pending-user-input-toggle]").waitFor({ state: "hidden" });
    } else {
      await app.screenshot(`${item.id}-choices`);
    }
    outcomes[item.id] = JSON.parse((await FS.readFile(responseLog, "utf8")).trim());
  }
  await FS.writeFile(Path.join(T3_HOME, "elicitation-outcomes.json"), JSON.stringify(outcomes, null, 2));
  await expect(outcomes).toEqual({
    single: { action: "accept", content: { mode: "" } },
    control: { action: "accept", content: { mode: "" } },
    multi: { action: "accept", content: { tags: [""] } },
  });
});
