/**
 * Generate an interactive HTML report from the visual parity JSON output.
 *
 * Reads comparison-report/visual/report.json and the HTML template,
 * injects the data, fixes image paths to be relative, and writes
 * comparison-report/visual/report.html.
 *
 * Usage:
 *   npx tsx tests/parity/visual/generate-report.ts
 */

import { readFileSync, writeFileSync } from "node:fs";
import { resolve, relative } from "node:path";
import type { MultiViewportReport } from "./screenshot-diff-multi.js";

const ROOT = resolve(import.meta.dirname, "../../..");
const REPORT_DIR = resolve(ROOT, "comparison-report/visual");
const REPORT_JSON = resolve(REPORT_DIR, "report.json");
const TEMPLATE_PATH = resolve(import.meta.dirname, "report-template.html");
const OUTPUT_PATH = resolve(REPORT_DIR, "report.html");

// Read inputs
const report: MultiViewportReport = JSON.parse(readFileSync(REPORT_JSON, "utf-8"));
const template = readFileSync(TEMPLATE_PATH, "utf-8");

// Fix image paths: convert absolute paths to relative from the report HTML location
for (const result of report.results) {
  result.angularPath = relative(REPORT_DIR, result.angularPath);
  result.reactPath = relative(REPORT_DIR, result.reactPath);
  result.diffPath = relative(REPORT_DIR, result.diffPath);
}

// Inject data and write
const html = template.replace("%%DATA%%", JSON.stringify(report, null, 2));
writeFileSync(OUTPUT_PATH, html, "utf-8");

console.log(`Report written to ${OUTPUT_PATH}`);
console.log(`  Routes: ${new Set(report.results.map((r) => r.route)).size}`);
console.log(`  Viewports: ${Object.keys(report.viewports).length}`);
console.log(`  Total comparisons: ${report.results.length}`);
