import { readFile, utimes } from "node:fs/promises";
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 { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Explicit Cursor and Grok provider display names survive saving", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("provider-names");
  await t3.open("/settings/providers");
  await screen.getByRole("button", "Add provider", { exact: true }).first().tap();
  await screen.getByRole("radio", "Grok Build", { exact: true }).tap();
  await screen.getByRole("button", "Next", { exact: true }).tap();
  await browser.locator("#add-provider-label").fill("Cursor");
  await browser.locator("#add-provider-instance-id").fill("name-cursor");
  await screen.getByRole("button", "Next", { exact: true }).tap();
  await screen.getByRole("button", "Add instance", { exact: true }).tap();
  await t3.open("/settings/providers?instanceId=name-cursor");
  const cursor = browser.locator("#provider-instance-name-cursor-display-name");
  await cursor.waitFor();
  await app.screenshot("Cursor-after-add");
  const created = JSON.parse(await readFile(`${T3_HOME}/userdata/settings.json`, "utf8")).providerInstances["name-cursor"].displayName;
  await cursor.fill("Cursor Work");
  await cursor.press("Tab");
  await expect.poll(async () => JSON.parse(await readFile(`${T3_HOME}/userdata/settings.json`, "utf8")).providerInstances["name-cursor"].displayName).toBe("Cursor Work");
  for (const [id, driver, name] of [["name-grok", "grok", "Grok Old"]]) {
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
        operation: "upsert", instanceId: ProviderInstanceId.make(id!),
        instance: { driver: ProviderDriverKind.make(driver!), displayName: name!, enabled: false, config: {} },
      }});
    }).pipe(Effect.scoped));
  }
  const actual: string[] = [];
  for (const [id, name] of [["name-cursor", "Cursor"], ["name-grok", "Grok"]]) {
    await t3.open(`/settings/providers?instanceId=${id}`);
    const input = browser.locator(`#provider-instance-${id}-display-name`);
    await input.fill(name!);
    await input.press("Tab");
    // Reopen from the server-backed settings route after the save has reached disk.
    await expect.poll(async () => {
      const settings = JSON.parse(await readFile(`${T3_HOME}/userdata/settings.json`, "utf8"));
      return settings.providerInstances[id!].displayName !== (id === "name-cursor" ? "Cursor Work" : "Grok Old");
    }).toBe(true);
    await t3.open(`/settings/providers?instanceId=${id}`);
    await input.waitFor();
    await app.screenshot(`${name}-after-save`);
    const settings = JSON.parse(await readFile(`${T3_HOME}/userdata/settings.json`, "utf8"));
    actual.push(settings.providerInstances[id!].displayName);
  }
  // The dev launcher restarts the real server when a source file changes; no source content changes.
  const runtimePath = `${T3_HOME}/userdata/server-runtime.json`;
  const previous = JSON.parse(await readFile(runtimePath, "utf8"));
  const now = new Date();
  await utimes(`${APP_DIR}/apps/server/src/bin.ts`, now, now);
  await expect.poll(async () => {
    try {
      const next = JSON.parse(await readFile(runtimePath, "utf8"));
      return next.pid !== previous.pid && next.startedAt !== previous.startedAt;
    } catch { return false; }
  }, { timeout: 60000 }).toBe(true);
  const afterRestart: string[] = [];
  for (const [id, name] of [["name-cursor", "Cursor"], ["name-grok", "Grok"]]) {
    await t3.open(`/settings/providers?instanceId=${id}`);
    await browser.locator(`#provider-instance-${id}-display-name`).waitFor();
    await app.screenshot(`${name}-after-server-restart`);
    const settings = JSON.parse(await readFile(`${T3_HOME}/userdata/settings.json`, "utf8"));
    afterRestart.push(settings.providerInstances[id!].displayName);
  }
  expect({ created, afterSave: actual, afterRestart }).toEqual({ created: "Cursor", afterSave: ["Cursor", "Grok"], afterRestart: ["Cursor", "Grok"] });
});
