#!/usr/bin/env node
// Real browser verification of public/tools/battery-quote-check/.
// Uses an installed Playwright. No package installation or service is required.
//   node research/battery-quote-check/verify-browser.mjs
//   node research/battery-quote-check/verify-browser.mjs --base-url=https://artwaste.land --output-dir=/tmp/battery-browser
// Optional: --playwright=/path/to/playwright/index.mjs --chromium=/path/to/chrome
// Screenshots and reader downloads go to /tmp by default. All checks always run.
import assert from 'node:assert/strict';
import http from 'node:http';
import { readFile, mkdir, mkdtemp, writeFile, stat } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import path from 'node:path';
import os from 'node:os';
import { performance } from 'node:perf_hooks';
import { makeDemo } from '../../public/tools/battery-quote-check/demo.mjs';
import { buildModel, evaluateModel } from '../../public/tools/battery-quote-check/engine.mjs';
import { verifyReport } from '../../public/tools/battery-quote-check/audit.mjs';
import { formatDecimal } from '../../public/tools/battery-quote-check/rational.mjs';

const arg = (name) => process.argv.find((s) => s.startsWith(`--${name}=`))?.slice(name.length + 3);
const ROOT = fileURLToPath(new URL('../../', import.meta.url)), PUBLIC = path.join(ROOT, 'public');
const OUTPUT = arg('output-dir') || await mkdtemp(path.join(os.tmpdir(), 'battery-browser-'));
await mkdir(OUTPUT, { recursive: true });
let pw;
for (const candidate of [arg('playwright'), 'playwright', '/home/liam/tools/node_modules/playwright/index.mjs'].filter(Boolean)) {
  try { pw = await import(candidate.startsWith('/') ? pathToFileURL(candidate).href : candidate); break; } catch {}
}
if (!pw) throw new Error('Install/provide Playwright separately, then pass --playwright=/path/to/index.mjs. This verifier does not install dependencies.');
const TYPES = { '.html': 'text/html', '.mjs': 'text/javascript', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json',
  '.woff2': 'font/woff2', '.woff': 'font/woff', '.png': 'image/png', '.svg': 'image/svg+xml', '.csv': 'text/csv', '.zip': 'application/zip' };
let server, browser;
let base = arg('base-url');
if (!base) {
  server = http.createServer(async (req, res) => {
    try {
      let pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
      if (pathname.endsWith('/')) pathname += 'index.html';
      const filename = path.resolve(PUBLIC, '.' + pathname);
      if (!filename.startsWith(PUBLIC + path.sep)) throw new Error('outside public');
      const body = await readFile(filename);
      res.writeHead(200, { 'content-type': TYPES[path.extname(filename)] || 'application/octet-stream' }); res.end(body);
    } catch { res.writeHead(404); res.end('not found'); }
  });
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
  base = `http://127.0.0.1:${server.address().port}`;
}
const TOOL = new URL('/tools/battery-quote-check/', base).href;
const CANARY = '0.123456789', PRIVATE_NAME = 'PRIVATE-BATTERY-READER-72931.csv';
const requests = [], errors = [], downloads = [], timings = [];
let passed = 0;
const equal = (a, b, label) => { assert.equal(a, b, label); passed++; };
const truth = (a, label) => { assert.ok(a, label); passed++; };
const checkText = async (page, selector, value) => equal((await page.locator(selector).textContent()).trim(), value, selector);
const moneyUp = (value) => '$' + Number(formatDecimal(value, 2, 'up')).toLocaleString('en-AU', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const HEAD = 'start,durationMinutes,importKwh,exportKwh';
const CSV = `${HEAD}\n2026-01-01T00:00:00Z,60,0,1\n2026-01-01T01:00:00Z,60,1,0\n`;
function nemFixture(quality = 'A') {
  const channel = (s) => `200,VABD000163,E1B1,${s},${s},N1,QMETER72931,kWh,30,20260401`;
  const day = (v) => ['300', '20260101', ...Array(48).fill(v), quality, '', '', '20260103003000', ''].join(',');
  return ['100,NEM12,202601031234,MDP1,RETAILER1', channel('E1'), day('0.1'), channel('B1'), day('0.2'), '900'].join('\r\n') + '\r\n';
}
async function ready(page) { await page.waitForFunction(() => document.getElementById('certificate-state').textContent === 'Exact certificate passed', { timeout: 90000 }); }
async function recalculate(page) { await page.click('#run'); await ready(page); }
async function uploadCsv(page, text = CSV, name = PRIVATE_NAME) {
  await page.setInputFiles('#meter-file', { name, mimeType: 'text/csv', buffer: Buffer.from(text) });
  await page.waitForFunction(() => !document.getElementById('data-note').textContent.includes('Reading local'));
  await page.selectOption('#offset', '0');
  await recalculate(page);
}
async function downloaded(page, id) {
  const pending = page.waitForEvent('download'); await page.click(id); const download = await pending;
  const target = path.join(OUTPUT, download.suggestedFilename()); await download.saveAs(target);
  downloads.push(download.suggestedFilename()); return { target, text: await readFile(target, 'utf8') };
}

try {
  browser = await pw.chromium.launch({ headless: true, args: ['--no-sandbox'], ...(arg('chromium') ? { executablePath: arg('chromium') } : {}) });
  const context = await browser.newContext({ viewport: { width: 1440, height: 1100 }, locale: 'en-AU', acceptDownloads: true });
  const page = await context.newPage();
  page.on('pageerror', (error) => errors.push(error.message));
  page.on('request', (request) => requests.push({ url: request.url(), method: request.method(), body: request.postData() || '' }));
  await page.goto(TOOL, { waitUntil: 'networkidle' }); await ready(page);
  const expectedDemo = evaluateModel(buildModel({ intervals: makeDemo().intervals, capacityKwh: '10', chargePowerKw: '5', dischargePowerKw: '5',
    chargeEfficiency: '0.9', dischargeEfficiency: '1', tariffs: { buyRate: '0.32', feedInRate: '0.05' } }));
  await checkText(page, '#upper', moneyUp(expectedDemo.summary.upper));
  truth((await page.locator('#period').textContent()).includes('INVENTED EXAMPLE'), 'demo provenance is prominent');
  truth((await page.locator('#data-note').textContent()).includes('17,520'), 'demo year really loaded');
  await page.screenshot({ path: path.join(OUTPUT, 'desktop.png'), fullPage: true });
  await page.screenshot({ path: path.join(OUTPUT, 'hero.png'), clip: { x: 0, y: 0, width: 1440, height: 1000 } });
  console.log(`VISUALS ${OUTPUT}/desktop.png ${OUTPUT}/hero.png`);

  await page.fill('#capacity', '12');
  await checkText(page, '#certificate-state', 'Recalculate changes');
  truth(await page.locator('#export-report').isDisabled(), 'dirty settings disable report export');
  equal(await page.locator('#verdict').getAttribute('data-status'), 'stale', 'dirty quote comparison is visibly stale');
  await page.fill('#capacity', '0'); await page.click('#run');
  truth((await page.locator('#run-status').textContent()).includes('Check'), 'invalid capacity is refused');
  await page.fill('#capacity', '10'); await recalculate(page);
  await page.locator('#demo').focus(); await page.keyboard.press('Enter'); await ready(page);
  truth(await page.locator('#demo').evaluate((el) => getComputedStyle(el).outlineStyle !== 'none'), 'keyboard activation has a visible focus outline');

  await uploadCsv(page);
  await checkText(page, '#upper', '$0.32'); await checkText(page, '#policy', '$0.23');
  truth((await page.locator('#data-note').textContent()).startsWith('LOCAL FILE.'), 'real file is distinguished from demo');
  await page.fill('#quote', '1');
  equal(await page.locator('#verdict').getAttribute('data-status'), 'not-comparable', 'unconfirmed quote scope is not compared');
  for (const id of ['existingSolar', 'completeMeter', 'sameAssumptions', 'excludedServices']) await page.check('#' + id);
  equal(await page.locator('#verdict').getAttribute('data-status'), 'exceeds', 'quote above exact ceiling is identified');
  await page.fill('#quote', '0.32');
  equal(await page.locator('#verdict').getAttribute('data-status'), 'not-ruled-out', 'equality is not ruled out');
  await page.fill('#quote', '0.33');
  equal(await page.locator('#verdict').getAttribute('data-status'), 'exceeds', 'one cent above is rejected under matched scope');

  await page.click('#compare'); await ready(page);
  await page.waitForFunction(() => document.getElementById('compare-status').textContent === 'All displayed capacities checked.');
  truth(await page.locator('#capacity-table').isVisible(), 'capacity comparison renders a table');
  truth((await page.locator('#capacity-table').textContent()).includes('0.00'), 'physical no-battery row is zero');
  const saved = await downloaded(page, '#export-report'), report = JSON.parse(saved.text);
  equal(verifyReport(report).summary.upper, '8/25', 'downloaded JSON independently reproduces exact result');
  equal(report.certificate.model.intervals.length, 2, 'download includes the actual imported readings');
  equal(report.context.synthetic, false, 'download does not mislabel real readings as synthetic');
  truth(!saved.text.includes('QMETER72931') && !saved.text.includes(PRIVATE_NAME), 'download does not include source filename or meter identity');
  const reader = await mkdtemp(path.join(OUTPUT, 'reader-'));
  for (const file of ['check-report.mjs', 'audit.mjs', 'certificate.mjs', 'rational.mjs']) {
    const response = await context.request.get(new URL(file, TOOL).href); equal(response.status(), 200, `${file} is obtainable by a reader`);
    await writeFile(path.join(reader, file), await response.body());
  }
  await writeFile(path.join(reader, 'battery-report.json'), saved.text);
  const stdout = execFileSync(process.execPath, ['check-report.mjs', 'battery-report.json'], { cwd: reader, encoding: 'utf8' });
  equal(JSON.parse(stdout).upperExact, '8/25', 'downloaded checker runs in an empty directory without the repository');
  const dispatch = await downloaded(page, '#export-csv');
  equal(dispatch.text.trim().split('\n').length, 3, 'dispatch export has exactly two data rows');
  truth(dispatch.text.startsWith(HEAD + ',buyRate,feedInRate,chargeKwh'), 'dispatch export names its units/fields');
  const summary = await downloaded(page, '#export-text');
  truth(summary.text.includes('Exact ceiling: 8/25 AUD'), 'text export preserves exact ceiling');
  await page.locator('summary').filter({ hasText: 'Check a saved report here' }).click();
  await page.setInputFiles('#verify-file', { name: 'saved.json', mimeType: 'application/json', buffer: Buffer.from(saved.text) });
  await page.waitForFunction(() => document.getElementById('verify-status').textContent.startsWith('PASS:'));
  const forged = structuredClone(report); forged.certificate.claims.upper = '0';
  await page.setInputFiles('#verify-file', { name: 'forged.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(forged)) });
  await page.waitForFunction(() => document.getElementById('verify-status').textContent.startsWith('FAILED:'));
  truth((await page.locator('#verify-status').textContent()).includes('Claim upper'), 'forged report fails on its actual altered assertion');
  console.log('PASS demo, dirty settings, CSV, quote comparisons, exports, empty-directory CLI and forged report');

  await page.setInputFiles('#meter-file', { name: 'bad.csv', mimeType: 'text/csv', buffer: Buffer.from(CSV.replace(',60,1,0', ',60,-1,0')) });
  await page.waitForFunction(() => document.getElementById('import-status').classList.contains('error'));
  truth(await page.locator('#run').isDisabled(), 'rejected import disables calculation');
  truth(await page.locator('#export-report').isDisabled(), 'rejected import disables old report downloads');

  await page.setInputFiles('#meter-file', { name: 'meter.nem12', mimeType: 'text/plain', buffer: Buffer.from(nemFixture()) });
  await page.waitForSelector('#nem-controls:not([hidden])');
  await page.selectOption('#offset', '600');
  await page.selectOption('#import-channel', 'channel-1'); await page.selectOption('#export-channel', 'channel-2');
  await page.click('#load-nem'); await ready(page);
  truth((await page.locator('#data-note').textContent()).includes('48 contiguous'), 'NEM12 pair really becomes 48 intervals');
  await checkText(page, '#upper', '$1.54');
  truth(!(await page.locator('body').textContent()).includes('QMETER72931'), 'meter serial is not displayed');
  await page.selectOption('#offset', '570');
  truth(await page.locator('#run').isDisabled(), 'changing NEM12 clock demands a fresh file/channel interpretation');

  const override = CSV.replace(HEAD, HEAD + ',buyRate,feedInRate').replace(',60,0,1\n', ',60,0,1,0.75,0\n').replace(',60,1,0\n', ',60,1,0,0.75,0\n');
  await uploadCsv(page, override); await checkText(page, '#upper', '$0.75');
  truth(await page.locator('#rate-note').isVisible(), 'CSV rate overrides are disclosed');

  const canaryCsv = `${HEAD}\n2026-01-01T00:00:00Z,60,${CANARY},0\n`;
  await uploadCsv(page, canaryCsv);
  const leak = (r) => [CANARY, PRIVATE_NAME, 'QMETER72931'].some((s) => r.url.includes(s) || r.body.includes(s));
  truth(!requests.some(leak), 'no request URL or body contains private input canaries');
  truth(leak({ url: 'https://example.invalid/', body: CANARY }), 'the privacy detector can actually detect a body leak');
  const stored = await page.evaluate(() => [...Object.entries(localStorage), ...Object.entries(sessionStorage)].map(([k, v]) => k + v).join('\n'));
  truth(!stored.includes(CANARY) && !stored.includes(PRIVATE_NAME), 'meter data are not put in browser storage');
  console.log('PASS NEM12, clock invalidation, tariff override and private-data checks');

  // A complete five-minute year through real file import, UI and Worker.
  const n = 105120, first = Date.UTC(2025, 0, 1);
  const year = HEAD + '\n' + Array.from({ length: n }, (_, k) => `${new Date(first + k * 300000).toISOString()},5,${k % 12 < 6 ? '0.2,0' : '0,0.3'}`).join('\n') + '\n';
  const started = performance.now(); await uploadCsv(page, year, 'synthetic-full-year.csv');
  timings.push({ scenario: '105120 rows through file input and Worker', milliseconds: Math.round(performance.now() - started) });
  truth((await page.locator('#data-note').textContent()).includes('105,120'), 'full five-minute year processed in app Worker');
  truth(await page.locator('#export-report').isEnabled(), 'full-year certificate enables export');

  await page.click('#demo'); await ready(page);
  for (const width of [390, 768, 1440]) {
    await page.setViewportSize({ width, height: width === 390 ? 844 : 1100 });
    await page.waitForTimeout(100);
    const overflow = await page.evaluate(() => ({ viewport: innerWidth, body: document.body.scrollWidth, document: document.documentElement.scrollWidth }));
    truth(overflow.body <= width + 1 && overflow.document <= width + 1, `no horizontal page overflow at ${width}px: ${JSON.stringify(overflow)}`);
    await page.screenshot({ path: path.join(OUTPUT, `viewport-${width}.png`), fullPage: true });
    if (width === 390) {
      await page.evaluate(() => window.scrollTo(0, 0));
      await page.screenshot({ path: path.join(OUTPUT, 'mobile-top.png') });
    }
    truth(await page.locator('#demo').isVisible(), `core controls remain available at ${width}px`);
  }
  // A browser zoom captures the actual title and demo result together at share size.
  // The candidate stays in /tmp until a human/agent has visually inspected it.
  await page.setViewportSize({ width: 1200, height: 630 });
  await page.evaluate(() => { document.documentElement.style.zoom = '0.8'; window.scrollTo(0, 0); });
  await page.screenshot({ path: path.join(OUTPUT, 'og-candidate.png') });
  equal(errors.length, 0, `no browser JavaScript exceptions: ${errors.join('; ')}`);
  const reportQA = { passed, baseURL: base, output: OUTPUT, browser: browser.version(), timings, downloads,
    requestMethods: [...new Set(requests.map((r) => r.method))], offOrigin: [...new Set(requests.filter((r) => !r.url.startsWith(new URL(base).origin)).map((r) => r.url))] };
  await writeFile(path.join(OUTPUT, 'qa-results.json'), JSON.stringify(reportQA, null, 2) + '\n');
  console.log(JSON.stringify(reportQA, null, 2));
} finally {
  if (browser) await browser.close();
  if (server) await new Promise((resolve) => server.close(resolve));
}
