import { expect } from 'e2e';
import { chromium } from 'playwright-core';
import { writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { test, WEB } from './t3.ts';
import { APP_DIR } from '../e2e.config.ts';

test('Usage figures expose individually navigable labels and values', WEB, async ({t3,app,browser,screen}) => {
  await t3.project('Usage accessibility demo');
  await t3.open('/usage');
  await screen.getByRole('button', 'Cost').tap();
  await screen.getByText('claude-sonnet-4-5', {exact:true}).tap();
  await app.screenshot('model-stat-tiles');
  await screen.getByRole('button', 'Close').last().tap();
  await app.screenshot('usage-summary-and-totals');
  const sha = execFileSync('git',['rev-parse','HEAD'],{cwd:APP_DIR,encoding:'utf8'}).trim();
  const out = `${process.env.USAGE_EVIDENCE_DIR}/${sha}`;
  const pw = await chromium.launch({headless:true});
  try {
    const context = await pw.newContext({viewport:{width:1280,height:800},colorScheme:'dark'});
    await context.addCookies(await browser.cookies());
    const page = await context.newPage();
    await page.goto(await browser.url());
    await page.getByRole('button',{name:'Cost',exact:true}).click();
    await page.getByText('claude-sonnet-4-5',{exact:true}).waitFor();
    const overview = await page.locator('body').ariaSnapshot();
    await page.getByText('claude-sonnet-4-5',{exact:true}).click();
    const dialog = page.getByRole('dialog');
    await dialog.waitFor();
    const stats = await dialog.ariaSnapshot();
    writeFileSync(out+'-accessibility.txt', 'USAGE PAGE\n'+overview+'\nMODEL DIALOG\n'+stats);
    const terms = await dialog.getByRole('term').count();
    const definitions = await dialog.getByRole('definition').count();
    writeFileSync(out+'-result.json', JSON.stringify({sha,terms,definitions,overview,stats},null,2));
    await expect(terms).toBeGreaterThanOrEqual(4);
    await expect(definitions).toBeGreaterThanOrEqual(4);
    await expect(overview).toContain('- term: Processed tokens');
    await expect(overview).toContain('- term: Claude Code 3 sessions');
    await expect(stats).toContain('- term: Cache hit');
  } finally { await pw.close(); }
});
