/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Usage hour endpoints distinguish dates across spring DST", WEB, async ({t3, app, browser, screen}) => {
  // Configure web() with locale: "en-US", timezoneId: "America/New_York".
  // Inherit CLAUDE_CONFIG_DIR into the app with T3_SCENARIO_INHERIT_ENV.
  const transcriptRoot = `${process.env.CLAUDE_CONFIG_DIR}/projects/usage-demo`;
  await fs.mkdir(transcriptRoot, {recursive: true});
  const samples = [
    ["2026-03-07T14:45:00Z", 1.11], ["2026-03-07T15:45:00Z", 2.22],
    ["2026-03-08T13:45:00Z", 3.33], ["2026-03-09T14:45:00Z", 4.44],
    ["2026-03-09T15:45:00Z", 5.55], ["2026-03-10T13:45:00Z", 6.66],
  ];
  await fs.writeFile(`${transcriptRoot}/usage-example.jsonl`, samples.map(([timestamp, costUSD], i) => JSON.stringify({
    type: "assistant", timestamp, costUSD, sessionId: "usage-example", requestId: `r${i}`,
    message: {id: `m${i}`, model: "claude-sonnet-4-5", role: "assistant", content: [],
      usage: {input_tokens: 100, output_tokens: 10}},
  })).join("\n") + "\n");
  const project = await t3.project("usage-demo");
  const thread = await t3.thread({project, title: "Usage example", messages: ["Hello"]});
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent.enabled = true;
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  await browser.addInitScript(() => {
    const RealDate = Date;
    const fixed = RealDate.parse(localStorage.getItem("scenario-now") ?? "2026-03-08T14:30:00Z");
    class FrozenDate extends RealDate {
      constructor(...args: any[]) { super(...(args.length ? args : [fixed]) as [any]); }
      static now() { return fixed; }
    }
    window.Date = FrozenDate as DateConstructor;
  });
  await t3.open(thread);
  await t3.open("/settings/general");
  await screen.getByRole("combobox", "Timestamp format").tap();
  await screen.getByRole("option", "12-hour", {exact: true}).tap();
  await t3.open("/usage");
  await screen.getByRole("button", "Allow", {exact: true}).tap();
  await screen.getByRole("button", /^Cost/).tap();
  await screen.getByRole("button", /^Past 24h/).tap();
  await screen.getByRole("button", "Hour", {exact: true}).tap();
  await screen.getByRole("cell", "$3.33", {exact: true}).first().waitFor();
  await browser.evaluate(() => {const tables = document.querySelectorAll("table"); tables[tables.length - 1].scrollIntoView({block: "end"}); return null;});
  await app.screenshot("spring-DST-hour-breakdown");
  const dstLabels = await browser.evaluate(() => Array.from(document.querySelectorAll("table")[document.querySelectorAll("table").length - 1].querySelectorAll("tbody tr"), row => row.querySelector("td")?.textContent?.trim() ?? ""));
  // Capture the same ordinary-day control before checking the broken DST labels.
  await browser.evaluate(() => {localStorage.setItem("scenario-now", "2026-03-10T14:30:00Z"); return null;});
  await t3.open("/usage");
  await screen.getByRole("button", "Hour", {exact: true}).tap();
  await screen.getByRole("cell", "$6.66", {exact: true}).first().waitFor();
  await browser.evaluate(() => {const tables = document.querySelectorAll("table"); tables[tables.length - 1].scrollIntoView({block: "end"}); return null;});
  await app.screenshot("ordinary-day-hour-breakdown");
  const controlLabels = await browser.evaluate(() => Array.from(document.querySelectorAll("table")[document.querySelectorAll("table").length - 1].querySelectorAll("tbody tr"), row => row.querySelector("td")?.textContent?.trim() ?? ""));
  expect(controlLabels).toEqual(["9 AM", "11 AM", "10 AM"]);
  expect(dstLabels).toEqual(["Mar 8, 9 AM", "10 AM", "Mar 7, 9 AM"]);
});
