const fs = require('fs');
const path = require('path');
const { chromium } = require('playwright');

const url = process.argv[2] || 'http://127.0.0.1:5175/PACK_OPENING_REPLICATION_REPORT.html';
const outputDir = path.resolve(__dirname, '..', 'verification');
fs.mkdirSync(outputDir, { recursive: true });

async function verify(browser, name, viewport) {
  const page = await browser.newPage({ viewport });
  const errors = [];
  page.on('console', (message) => {
    if (message.type() === 'error') errors.push(`console: ${message.text()}`);
  });
  page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));
  page.on('requestfailed', (request) => errors.push(`request: ${request.url()} ${request.failure()?.errorText}`));

  await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 });
  await page.screenshot({ path: path.join(outputDir, `report-${name}-top.png`) });

  const stages = [];
  for (let index = 0; index < 5; index += 1) {
    await page.locator(`.stage-tab[data-stage="${index}"]`).click();
    await page.waitForFunction(() => [...document.images].every((image) => image.complete && image.naturalWidth > 0));
    stages.push(await page.evaluate(() => ({
      original: document.querySelector('#originalImage').getAttribute('src'),
      replica: document.querySelector('#replicaImage').getAttribute('src'),
      observation: document.querySelector('#stageObservation').textContent,
    })));
  }

  await page.locator('#comparison').scrollIntoViewIfNeeded();
  await page.screenshot({ path: path.join(outputDir, `report-${name}-comparison.png`) });
  const result = await page.evaluate(() => ({
    title: document.title,
    bodyWidth: document.body.scrollWidth,
    viewportWidth: window.innerWidth,
    brokenImages: [...document.images].filter((image) => !image.complete || image.naturalWidth === 0).map((image) => image.src),
    originalPreview: document.querySelector('a[href*="mockData=1"]')?.href,
  }));
  await page.close();
  return { name, viewport, errors, stages, ...result };
}

(async () => {
  const browser = await chromium.launch({
    headless: true,
    executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
  });
  try {
    const report = {
      url,
      desktop: await verify(browser, 'desktop', { width: 1440, height: 900 }),
      mobile: await verify(browser, 'mobile', { width: 390, height: 844 }),
    };
    fs.writeFileSync(path.join(outputDir, 'report-verification.json'), JSON.stringify(report, null, 2));
    process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
  } finally {
    await browser.close();
  }
})().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
