import { expect } from "e2e";
import { readFileSync, renameSync, mkdirSync, rmdirSync } from "node:fs";
import { join } from "node:path";
import { test, WEB } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("A failed custom model save retains its editable draft", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Custom model demo");
  await t3.open("/settings/providers");
  // Error descriptions contain the local settings path; retain the public error title in evidence.
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '[data-slot="toast-description"] { display: none !important; } input[value*="/"] { color: transparent !important; }';
    document.head.append(style);
  });
  await screen.getByRole("button", "Select Codex").tap();
  await screen.getByRole("button", "Add custom model").tap();
  const input = browser.locator("#provider-instance-codex-custom-model");
  const slug = "repro-custom-model-35176";
  await input.fill(slug);
  await app.screenshot("draft-before-save");
  const settings = join(T3_HOME, "userdata/settings.json");
  const backup = join(T3_HOME, "userdata/settings.proof-backup");
  readFileSync(settings);
  renameSync(settings, backup);
  mkdirSync(settings);
  try {
    await screen.getByRole("button", "Add", { exact: true }).tap();
    await screen.getByText("Could not update provider instance", { exact: true }).waitFor({ state: "visible" });
    await app.screenshot("failed-save-draft");
    await expect(input).toHaveValue(slug);
    await input.fill(`${slug}-edited`);
    await app.screenshot("editable-after-failure");
  } finally {
    rmdirSync(settings);
    renameSync(backup, settings);
  }
  await input.fill(slug);
  await screen.getByRole("button", "Add", { exact: true }).tap();
  await expect(input).not.toBeVisible();
  await app.screenshot("successful-save-control");
});
