// BroadbandSwitch.uk evidence capture script
// Captures timestamped, full-page screenshots of every source URL used in the
// verified deals review, so any journalist or reader can trace every figure.
//
// Setup (once):   npm init -y && npm install playwright && npx playwright install chromium
// Run (each review):   node capture-screenshots.mjs
//
// Reads evidence-urls.csv.  If exact_deal_url_paste_here is filled, that page is
// captured; otherwise the provider start_url is captured as the anchor.
// Output: screenshots/<date>_<slug>.png plus manifest.json with UTC timestamps.

import { chromium } from 'playwright';
import { readFileSync, writeFileSync, mkdirSync } from 'fs';

const CSV = 'evidence-urls.csv';
const OUT = 'screenshots';
const today = new Date().toISOString().slice(0, 10);

function parseCsv(text) {
  const [header, ...lines] = text.trim().split(/\r?\n/);
  const cols = header.split(',');
  return lines.map(line => {
    const cells = [];
    let cur = '', inQ = false;
    for (const ch of line) {
      if (ch === '"') { inQ = !inQ; continue; }
      if (ch === ',' && !inQ) { cells.push(cur); cur = ''; continue; }
      cur += ch;
    }
    cells.push(cur);
    return Object.fromEntries(cols.map((c, i) => [c, cells[i] ?? '']));
  });
}

const rows = parseCsv(readFileSync(CSV, 'utf8'));
mkdirSync(OUT, { recursive: true });
const manifest = [];

const browser = await chromium.launch();
const context = await browser.newContext({
  viewport: { width: 1440, height: 900 },
  locale: 'en-GB',
  timezoneId: 'Europe/London',
});

for (const row of rows) {
  const url = row.exact_deal_url_paste_here || row.start_url;
  const file = `${OUT}/${today}_${row.screenshot_slug}.png`;
  const page = await context.newPage();
  try {
    await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });
    await page.waitForTimeout(3500);
    // Best-effort cookie banner dismissal.  Review captures manually afterwards.
    for (const label of ['Accept all', 'Accept All', 'Accept all cookies', 'I accept', 'Accept', 'Allow all', 'OK']) {
      const btn = page.getByRole('button', { name: label }).first();
      if (await btn.isVisible().catch(() => false)) { await btn.click().catch(() => {}); break; }
    }
    await page.waitForTimeout(1500);
    await page.screenshot({ path: file, fullPage: true });
    manifest.push({ provider: row.provider, label: row.label, url, file, captured_utc: new Date().toISOString(), status: 'captured' });
    console.log(`Captured  ${row.provider}  ${row.label}`);
  } catch (err) {
    manifest.push({ provider: row.provider, label: row.label, url, file: null, captured_utc: new Date().toISOString(), status: `failed: ${err.message}` });
    console.log(`FAILED    ${row.provider}  ${row.label}  ${err.message}`);
  }
  await page.close();
}

await browser.close();
writeFileSync(`${OUT}/manifest.json`, JSON.stringify(manifest, null, 2));
console.log(`\nDone.  ${manifest.filter(m => m.status === 'captured').length} of ${manifest.length} captured.  Review each image before publishing the pack.`);
