#!/usr/bin/env node

/**
 * Edikka Web Image Evidence Collector v1.1
 *
 * Collects public/browser evidence. It deliberately does not turn that evidence
 * into a global score and does not sign human, pipeline, Search Console or log
 * controls. Requires Node.js 20+ and Playwright.
 *
 * Usage:
 *   npm install playwright
 *   npx playwright install chromium
 *   node collect-image-evidence-edikka-v1-1.mjs https://example.com report.json
 */

import fs from 'node:fs/promises';
import process from 'node:process';
import { chromium } from 'playwright';

const targetUrl = process.argv[2];
const outputPath = process.argv[3] || 'web-image-evidence.json';

if (!targetUrl || !/^https?:\/\//i.test(targetUrl)) {
  throw new Error('Usage: node collect-image-evidence-edikka-v1-1.mjs <https://url> [report.json]');
}

const viewport = {
  width: Number(process.env.IMAGE_AUDIT_WIDTH || 1440),
  height: Number(process.env.IMAGE_AUDIT_HEIGHT || 1000),
};
const deviceScaleFactor = Number(process.env.IMAGE_AUDIT_DPR || 1);
const browser = await chromium.launch({
  headless: true,
  ...(process.env.IMAGE_AUDIT_CHROMIUM_EXECUTABLE
    ? { executablePath: process.env.IMAGE_AUDIT_CHROMIUM_EXECUTABLE }
    : {}),
});

try {
  const context = await browser.newContext({
    viewport,
    deviceScaleFactor,
    reducedMotion: 'reduce',
  });
  const page = await context.newPage();
  const responseHeaders = new Map();
  const consoleIssues = [];

  page.on('response', async (response) => {
    const request = response.request();
    if (request.resourceType() !== 'image') return;
    responseHeaders.set(response.url(), {
      status: response.status(),
      headers: await response.allHeaders(),
    });
  });
  page.on('console', (message) => {
    if (['warning', 'error'].includes(message.type())) {
      consoleIssues.push({ type: message.type(), text: message.text() });
    }
  });
  page.on('pageerror', (error) => consoleIssues.push({ type: 'pageerror', text: error.message }));

  const documentResponse = await page.goto(targetUrl, { waitUntil: 'networkidle', timeout: 45000 });
  if (!documentResponse) throw new Error('The navigation returned no document response.');

  await page.evaluate(async () => {
    if (document.fonts?.ready) await document.fonts.ready;
    const wait = (duration) => new Promise((resolve) => setTimeout(resolve, duration));
    const step = Math.max(400, Math.round(innerHeight * 0.75));
    const maximum = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
    let passes = 0;
    for (let y = 0; y < maximum && passes < 120; y += step, passes += 1) {
      scrollTo(0, y);
      await wait(60);
    }
    scrollTo(0, 0);
    await Promise.all(Array.from(document.images).map((image) => image.decode?.().catch(() => {})));
  });
  await page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => {});

  const observation = await page.evaluate(async () => {
    const resources = new Map(
      performance.getEntriesByType('resource')
        .filter((entry) => entry.initiatorType === 'img' || /\.(?:avif|webp|jpe?g|png|gif|svg)(?:\?|$)/i.test(entry.name))
        .map((entry) => [entry.name, {
          transfer_size_bytes: entry.transferSize,
          encoded_body_size_bytes: entry.encodedBodySize,
          decoded_body_size_bytes: entry.decodedBodySize,
          initiator_type: entry.initiatorType,
          start_time_ms: Math.round(entry.startTime * 100) / 100,
          duration_ms: Math.round(entry.duration * 100) / 100,
        }]),
    );

    const measureSelectedFile = async (selectedUrl) => {
      if (!selectedUrl) {
        return {
          width_px: null,
          height_px: null,
          method: null,
          error: 'No selected resource URL.',
        };
      }

      try {
        const response = await fetch(selectedUrl, { cache: 'force-cache', credentials: 'same-origin' });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const bitmap = await createImageBitmap(await response.blob());
        const dimensions = {
          width_px: bitmap.width,
          height_px: bitmap.height,
          method: 'createImageBitmap(fetch(currentSrc))',
          error: null,
        };
        bitmap.close();
        return dimensions;
      } catch (fetchError) {
        try {
          const probe = new Image();
          probe.decoding = 'async';
          probe.src = selectedUrl;
          await probe.decode();
          return {
            width_px: probe.naturalWidth,
            height_px: probe.naturalHeight,
            method: 'detached Image without srcset',
            error: null,
          };
        } catch (decodeError) {
          return {
            width_px: null,
            height_px: null,
            method: null,
            error: `fetch: ${fetchError.message}; decode: ${decodeError.message}`,
          };
        }
      }
    };

    const images = await Promise.all(Array.from(document.images).map(async (image, index) => {
      const rect = image.getBoundingClientRect();
      const resource = resources.get(image.currentSrc) || null;
      const selectedFile = await measureSelectedFile(image.currentSrc);
      const requiredWidth = rect.width > 0 ? rect.width * devicePixelRatio : null;
      const coverageRatio = requiredWidth && selectedFile.width_px
        ? selectedFile.width_px / requiredWidth
        : null;
      return {
        index: index + 1,
        src: image.getAttribute('src'),
        current_src: image.currentSrc,
        srcset: image.getAttribute('srcset'),
        sizes: image.getAttribute('sizes'),
        alt_present: image.hasAttribute('alt'),
        alt: image.getAttribute('alt'),
        role: image.getAttribute('role'),
        loading: image.loading || null,
        decoding: image.decoding || null,
        fetch_priority: image.fetchPriority || null,
        width_attribute: image.getAttribute('width'),
        height_attribute: image.getAttribute('height'),
        rendered_width_css_px: Math.round(rect.width * 100) / 100,
        rendered_height_css_px: Math.round(rect.height * 100) / 100,
        natural_width_css_px: image.naturalWidth,
        natural_height_css_px: image.naturalHeight,
        selected_file_width_px: selectedFile.width_px,
        selected_file_height_px: selectedFile.height_px,
        selected_file_dimension_method: selectedFile.method,
        selected_file_dimension_error: selectedFile.error,
        required_width_device_px: requiredWidth === null ? null : Math.round(requiredWidth * 100) / 100,
        candidate_coverage_ratio: coverageRatio === null ? null : Math.round(coverageRatio * 10000) / 10000,
        complete: image.complete,
        picture_sources: image.closest('picture')
          ? Array.from(image.closest('picture').querySelectorAll('source')).map((source) => ({
              type: source.type || null,
              media: source.media || null,
              srcset: source.srcset || null,
              sizes: source.sizes || null,
            }))
          : [],
        resource_timing: resource,
      };
    }));

    return {
      document: {
        title: document.title,
        lang: document.documentElement.lang,
        canonical: document.querySelector('link[rel="canonical"]')?.href || null,
        robots: document.querySelector('meta[name="robots"]')?.content || null,
      },
      viewport: {
        width: innerWidth,
        height: innerHeight,
        device_pixel_ratio: devicePixelRatio,
        horizontal_overflow_px: Math.max(document.documentElement.scrollWidth, document.body.scrollWidth) - document.documentElement.clientWidth,
      },
      counts: {
        images: images.length,
        pictures: document.querySelectorAll('picture').length,
        images_without_alt_attribute: images.filter((image) => !image.alt_present).length,
        images_without_explicit_dimensions: images.filter((image) => !image.width_attribute || !image.height_attribute).length,
        lazy_images: images.filter((image) => image.loading === 'lazy').length,
      },
      images,
      duplicate_ids: Array.from(document.querySelectorAll('[id]'))
        .map((element) => element.id)
        .filter((id, index, ids) => ids.indexOf(id) !== index),
    };
  });

  const imageResponses = Object.fromEntries(responseHeaders);
  for (const image of observation.images) {
    image.http = imageResponses[image.current_src] || null;
  }

  const report = {
    schema: 'https://www.edikka.com/docbd/data/web-image-evidence-report-v1-1.schema.json',
    collector: {
      name: 'Edikka Web Image Evidence Collector',
      version: '1.1',
      method_version: '1.1',
      method: 'https://www.edikka.com/en/insights/web-development/web-image-optimisation',
      license: 'https://creativecommons.org/licenses/by/4.0/',
    },
    observed_at: new Date().toISOString(),
    target_url: targetUrl,
    document_response: {
      status: documentResponse.status(),
      url: documentResponse.url(),
      headers: await documentResponse.allHeaders(),
    },
    ...observation,
    console_issues: consoleIssues,
    decision: {
      status: 'Not tested',
      reason: 'The collector publishes evidence only. IMGxx decisions requiring human, pipeline, Search Console or log access remain unsigned.',
    },
    limitations: [
      'One run describes one viewport, DPR, cache state and moment.',
      'The collector scrolls through the document to trigger native lazy loading before recording currentSrc.',
      'naturalWidth is density-corrected by the browser and is not used as the encoded file width for IMG07.',
      'The selected file is decoded independently from currentSrc; a failed fetch or decode leaves IMG07 evidence incomplete.',
      'Candidate coverage is an observation, not a pass/fail result: the applicable threshold remains versioned by image role.',
      'Performance entries can expose zero transfer bytes when cache or cross-origin timing restrictions apply.',
      'Alternative-text quality, crop, perceptual quality and editorial meaning require human review.',
      'Field Core Web Vitals, Search Console, server logs, source masters and encoder settings are outside public browser scope.',
    ],
  };

  await fs.writeFile(outputPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
  process.stdout.write(`${JSON.stringify({ output: outputPath, images: observation.counts.images, decision: report.decision.status }, null, 2)}\n`);
  await context.close();
} finally {
  await browser.close();
}
