import { expect } from "e2e";

import { test, WEB } from "./t3.ts";

const N = Number(process.env.SCRATCH_THREADS ?? 20);
const MESSAGES = Number(process.env.SCRATCH_MESSAGES ?? 3);

test("scratch: thread cache growth", WEB, async ({ t3, browser, screen }) => {
  const project = await t3.project("demo");
  const threads = [];
  const t0 = Date.now();
  for (let index = 1; index <= N; index += 1) {
    threads.push(
      await t3.thread({
        project,
        title: `Cache growth ${index}`,
        model: "showcase",
        messages: Array.from({ length: MESSAGES }, (_, m) => `message ${m}`),
      }),
    );
  }
  console.log(`SCRATCH seeded ${N} threads in ${Date.now() - t0} ms`);
  const measure = () =>
    browser.evaluate(
      () =>
        new Promise<string>((resolve, reject) => {
          const open = indexedDB.open("t3code:connection-runtime");
          open.onerror = () => reject(open.error);
          open.onsuccess = () => {
            const db = open.result;
            const out: Record<string, { count: number; chars: number }> = {};
            const names = Array.from(db.objectStoreNames);
            const tx = db.transaction(names, "readonly");
            for (const name of names) {
              const req = tx.objectStore(name).openCursor();
              out[name] = { count: 0, chars: 0 };
              req.onsuccess = () => {
                const cursor = req.result;
                if (!cursor) return;
                out[name]!.count += 1;
                const v = cursor.value;
                out[name]!.chars += typeof v === "string" ? v.length : JSON.stringify(v).length;
                cursor.continue();
              };
            }
            tx.oncomplete = () => {
              db.close();
              resolve(JSON.stringify(out));
            };
          };
        }),
    );
  for (const [index, thread] of threads.entries()) {
    await t3.open(thread);
    await expect(screen.getByText(`Cache growth ${index + 1}`).first()).toBeVisible();
    // Saves are debounced; give the persist queue time to drain before reading.
    await new Promise((resolve) => setTimeout(resolve, 1_500));
    console.log(`SCRATCH after-open ${index + 1} ${await measure()}`);
  }
  await t3.open();
  await new Promise((resolve) => setTimeout(resolve, 5_000));
  console.log(`SCRATCH after-reload ${await measure()}`);
});
