import { readFile, rename, mkdir, rmdir } from "node:fs/promises";
import { watch } from "node:fs";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("A failed new Usage period stops displaying the previous period as busy", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Usage proof");
  await t3.thread({project, title: "Usage sample", messages: ["Hello"], model: "default"});
  await t3.open("/usage");
  await screen.getByRole("button", "Cost", {exact:true}).click();
  await screen.getByRole("button", "30 days", {exact:true}).click();
  await browser.locator('div[aria-busy="false"].flex.flex-col.gap-6').waitFor();
  await app.screenshot("successful-30-day-period");
  const settings = `${T3_HOME}/userdata/settings.json`;
  const log = new URL("../.e2e/app.log", import.meta.url);
  const failedRead = new Promise<void>((resolve, reject) => {
    const timer = setTimeout(() => { watcher.close(); reject(new Error("Settings watcher did not report the read failure")); }, 15000);
    const watcher = watch(log, async () => {
      const text = await readFile(log, "utf8");
      if (text.includes("EISDIR")) { clearTimeout(timer); watcher.close(); resolve(); }
    });
  });
  await rename(settings, `${settings}.saved`);
  await mkdir(settings);
  try {
    await failedRead;
    await screen.getByRole("button", "7 days", {exact:true}).click();
    await browser.locator('[aria-label="Some environments could not report usage"]').waitFor();
    await app.screenshot("failed-7-day-period");
    await expect(browser.locator('div[aria-busy="true"].flex.flex-col.gap-6')).toHaveCount(0);
  } finally {
    await rmdir(settings);
    await rename(`${settings}.saved`, settings);
  }
});
