// Sequential, fresh-profile measurements of the deployed 2026 theme.
// Keep other browser workloads and deployments stopped during collection.
import assert from 'node:assert/strict';
import { execFileSync, spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import os from 'node:os';

const root = path.resolve(import.meta.dirname, '../..');
const require = createRequire(process.env.QUALITY_NODE_MODULES
  ? path.resolve(process.env.QUALITY_NODE_MODULES, '../package.json') : path.join(root, 'package.json'));
const { chromium } = require('playwright');
const axePath = require.resolve('axe-core/axe.min.js');
const lighthouseCli = path.join(path.dirname(require.resolve('lighthouse/package.json')), 'cli/index.js');
const base = process.env.QUALITY_BASE_URL || 'https://www.vargamae.ee';
const output = path.resolve(process.env.QUALITY_OUTPUT || path.join(root,
  'themes/vargamae-2026/quality/evidence', new Date().toISOString().replace(/[:.]/g, '-')));
assert(!existsSync(output), 'Use a new evidence directory. Completed or partial collections are never overwritten.');
const routes = [
  { id: 'home', path: '/', label: { et: 'Avaleht', en: 'Homepage' } },
  { id: 'education', path: '/oppekeskus/', label: { et: 'Õppekeskus', en: 'Education centre' } },
  { id: 'contact', path: '/hea-teada/kontakt/', label: { et: 'Kontakt', en: 'Contact' } },
];
const chromePath = process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const hash = data => createHash('sha256').update(data).digest('hex');
const hashFile = filename => hash(readFileSync(path.join(output, filename)));
const save = (filename, value) => writeFileSync(path.join(output, filename), JSON.stringify(value, null, 2) + '\n');
const curl = url => execFileSync('curl', ['--fail', '--location', '--silent', '--show-error', '--max-time', '60', url], { maxBuffer: 20_000_000 });
mkdirSync(output, { recursive: true });
const collection = {
  schemaVersion: 1, startedAt: new Date().toISOString(), completedAt: null,
  baseUrl: base, theme: 'vargamae-2026', deployedCommit: null,
  localReferenceCommit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(),
  tools: Object.fromEntries(['lighthouse', 'playwright', 'axe-core'].map(name => [name, require(`${name}/package.json`).version])),
  runner: { platform: os.platform(), architecture: os.arch(), node: process.version, chrome: execFileSync(chromePath, ['--version'], { encoding: 'utf8' }).trim() },
  methodology: {
    performance: 'Three sequential Lighthouse CLI runs per page and device with a fresh temporary Chrome profile. Standard simulated throttling, unmodified default mobile/desktop presets. Browser storage reset; server caches may be warm.',
    selection: 'The middle performance score of three runs, ordered by performance score then run number. Every displayed category and metric comes from that same actual run. All runs, ranges, warnings and failures are retained.',
    scope: 'Public production pages using the 2026 theme, including hosting, plugins, content and third-party services. No theme-only attribution and no historical comparison. Deployed Git revision is not exposed by the server; localReferenceCommit is not a deployment claim.',
    accessibility: 'One separate axe-core WCAG 2.0/2.1/2.2 A/AA scan per page/device, default light-mode page state, after a 5-second settling period. Open menus, dark mode, authenticated states and form flows are not included. Incomplete checks are retained for manual review.',
    interactions: 'Fresh unauthenticated visitor; no cookie choices, form submissions, scrolling, or other page interactions during measurement.',
    limitations: 'Lab observations, not visitor analytics or WCAG certification. Automated checks cannot establish full accessibility. Results vary with network, device, content and third-party behavior.',
  },
  routes: [], lighthouse: [], accessibility: [], artifacts: [],
};
const manifest = () => save('collection.json', collection);
try {
  for (const route of routes) {
    const url = new URL(route.path, base).href;
    const html = curl(url);
    assert(html.toString().includes('/themes/vargamae-2026/'), `Expected deployed 2026 theme at ${url}`);
    collection.routes.push({ ...route, url, htmlSha256Before: hash(html) });
  }
  const asset = '/wp-content/themes/vargamae-2026/asset/style/main.css';
  const remoteAsset = curl(new URL(asset, base).href);
  collection.themeAsset = {
    url: new URL(asset, base).href, sha256Before: hash(remoteAsset),
    localSha256: hash(readFileSync(path.join(root, 'themes/vargamae-2026/asset/style/main.css'))),
  };
  manifest();
  for (const profile of ['mobile', 'desktop']) for (const route of collection.routes) {
    for (let run = 1; run <= 3; run++) {
      const id = `${route.id}-${profile}-${run}`;
      const startedAt = new Date().toISOString();
      console.log(`Lighthouse ${id}: ${route.url}`);
      const args = [lighthouseCli, route.url, '--output=html', '--output=json',
        `--output-path=${path.join(output, id)}`, '--chrome-flags=--headless',
        '--only-categories=performance,accessibility,best-practices,seo',
        '--throttling-method=simulate', '--locale=en-US', '--no-enable-error-reporting', '--quiet',
        ...(profile === 'desktop' ? ['--preset=desktop'] : [])];
      await new Promise((resolve, reject) => {
        const child = spawn(process.execPath, args, { env: { ...process.env, CHROME_PATH: chromePath }, timeout: 240_000 });
        let log = '';
        child.stdout.on('data', part => { log += part; });
        child.stderr.on('data', part => { log += part; });
        child.once('error', reject);
        child.once('close', code => {
          writeFileSync(path.join(output, `${id}.log`), log);
          code === 0 ? resolve() : reject(new Error(`Lighthouse ${id} exited ${code}; see its log.`));
        });
      });
      const filename = `${id}.report.json`;
      const lhr = JSON.parse(readFileSync(path.join(output, filename)));
      assert(!lhr.runtimeError, JSON.stringify(lhr.runtimeError));
      assert.equal(new URL(lhr.finalDisplayedUrl).pathname, route.path, 'Unexpected measured page redirect');
      assert(lhr.categories.performance.score !== null, 'Missing performance score');
      const documentItem = lhr.audits['network-requests'].details.items.find(item => item.resourceType === 'Document');
      assert.equal(documentItem?.statusCode, 200, 'Main document did not return 200');
      const row = {
        id, route: route.id, profile, run, startedAt, fetchTime: lhr.fetchTime,
        finalUrl: lhr.finalDisplayedUrl, reportJson: filename, reportHtml: `${id}.report.html`,
        scores: Object.fromEntries(Object.entries(lhr.categories).map(([key, value]) => [key, Math.round(value.score * 100)])),
        metrics: Object.fromEntries(['first-contentful-paint', 'largest-contentful-paint', 'total-blocking-time', 'cumulative-layout-shift', 'speed-index', 'total-byte-weight'].map(key => [key, lhr.audits[key]?.numericValue ?? null])),
        settings: lhr.configSettings, warnings: lhr.runWarnings, jsonSha256: hashFile(filename), htmlSha256: hashFile(`${id}.report.html`),
      };
      collection.lighthouse.push(row);
      manifest();
      console.log(`  Performance ${row.scores.performance}; accessibility ${row.scores.accessibility}`);
    }
  }
  // Browser screenshots and axe run only after every timed Lighthouse run finishes.
  const browser = await chromium.launch({ executablePath: chromePath, headless: true });
  try {
    for (const profile of ['mobile', 'desktop']) for (const route of collection.routes) {
      const context = await browser.newContext({
        viewport: profile === 'mobile' ? { width: 412, height: 823 } : { width: 1350, height: 940 },
        isMobile: profile === 'mobile', deviceScaleFactor: 1, colorScheme: 'light', locale: 'et-EE',
      });
      const page = await context.newPage();
      const failedRequests = [];
      page.on('requestfailed', request => failedRequests.push({ url: request.url(), error: request.failure()?.errorText }));
      const response = await page.goto(route.url, { waitUntil: 'load', timeout: 90_000 });
      assert.equal(response.status(), 200);
      assert.equal(new URL(page.url()).pathname, route.path);
      await page.waitForTimeout(5000);
      const id = `${route.id}-${profile}`;
      await page.screenshot({ path: path.join(output, `${id}.png`), fullPage: false });
      await page.addScriptTag({ path: axePath });
      const result = await page.evaluate(async () => window.axe.run(document, {
        runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'] },
      }));
      const filename = `${id}.axe.json`;
      save(filename, result);
      collection.accessibility.push({
        id, route: route.id, profile, url: page.url(), timestamp: result.timestamp,
        engine: result.testEngine, environment: result.testEnvironment,
        viewport: page.viewportSize(), ruleFailures: result.violations.length,
        affectedNodes: result.violations.reduce((sum, rule) => sum + rule.nodes.length, 0),
        incompleteRules: result.incomplete.length, passedRules: result.passes.length,
        violations: result.violations.map(rule => ({ id: rule.id, impact: rule.impact, help: rule.help, helpUrl: rule.helpUrl, nodes: rule.nodes.length })),
        failedRequests, report: filename, screenshot: `${id}.png`, sha256: hashFile(filename), screenshotSha256: hashFile(`${id}.png`),
      });
      manifest();
      console.log(`axe ${id}: ${result.violations.length} rule failures, ${result.incomplete.length} need review`);
      await context.close();
    }
  } finally { await browser.close(); }
  collection.themeAsset.sha256After = hash(curl(collection.themeAsset.url));
  assert.equal(collection.themeAsset.sha256Before, collection.themeAsset.sha256After, 'Deployed CSS changed during collection');
  collection.completedAt = new Date().toISOString();
  manifest();
  console.log(`Completed: ${output}`);
} catch (error) {
  collection.error = { at: new Date().toISOString(), message: error.message };
  manifest();
  throw error;
}
