/**
 * verify-qr.js — 真实解码验证：对生成的静态 SVG 名牌解析出模块矩阵，
 * 转为 RGBA 像素后用独立解码库 jsQR 解码，验证二维码内容 === 报名码。
 * 运行：node tests/verify-qr.js
 * 说明：jsQR 仅用于本次验证，不在交付运行时依赖中。
 */
'use strict';
const fs = require('fs');
const path = require('path');
const jsQR = require('jsqr');

const BADGES = path.join(__dirname, '..', 'badges');
const CODES = {
  A01: 'CF27-A01-K7',
  A02: 'CF27-A02-M3',
  A03: 'CF27-A03-P8',
  A04: 'CF27-A04-R2',
  A05: 'CF27-A05-T4',
  A06: 'CF27-A06-W6'
};

/** 从 createSvgTag 生成的 path d 属性解析 dark 模块坐标："M2,2l4,0 0,4 -4,0 0,-4z" */
function parseMatrix(svg, cellSize, margin) {
  const m = svg.match(/viewBox="0 0 (\d+) (\d+)"/);
  const viewW = parseInt(m[1], 10);
  const count = Math.round((viewW - 2 * margin) / cellSize);
  const grid = Array.from({ length: count }, () => new Array(count).fill(false));
  const re = /M(\d+),(\d+)l/g;
  let hit;
  while ((hit = re.exec(svg))) {
    const x = parseInt(hit[1], 10), y = parseInt(hit[2], 10);
    const cx = Math.round((x - margin) / cellSize);
    const cy = Math.round((y - margin) / cellSize);
    grid[cy][cx] = true;
  }
  return grid;
}

let pass = 0, fail = 0;
for (const [id, expected] of Object.entries(CODES)) {
  try {
    const svg = fs.readFileSync(path.join(BADGES, id + '.svg'), 'utf8');
    const m = svg.match(/width="(\d+)px" height="(\d+)px" viewBox="0 0 (\d+) (\d+)"/);
    const cellSize = 4, margin = 0; // gen-badges 以 createSvgTag(4,0) 内嵌
    const grid = parseMatrix(svg, cellSize, margin);
    // 裁剪到 dark 模块的边界框，得到二维码本身的真实模块矩阵
    let minX = 1e9, minY = 1e9, maxX = -1, maxY = -1;
    grid.forEach((row, y) => row.forEach((dark, x) => {
      if (dark) { minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); }
    }));
    const count = maxX - minX + 1, rows = maxY - minY + 1;
    if (count !== rows) throw new Error(`二维码区域非正方形：${count}×${rows}`);
    const cells = [];
    for (let y = minY; y <= maxY; y++) cells.push(grid[y].slice(minX, maxX + 1));
    // 裁剪后的矩阵 → RGBA（scale=6, 周围留 4 模块白边，便于解码器定位）
    const scale = 6, border = 4;
    const size = (count + border * 2) * scale;
    const data = new Uint8ClampedArray(size * size * 4).fill(255);
    for (let y = 0; y < count; y++) {
      for (let x = 0; x < count; x++) {
        if (!cells[y][x]) continue;
        for (let dy = 0; dy < scale; dy++) {
          for (let dx = 0; dx < scale; dx++) {
            const px = (border + x) * scale + dx, py = (border + y) * scale + dy;
            const idx = (py * size + px) * 4;
            data[idx] = data[idx + 1] = data[idx + 2] = 0;
          }
        }
      }
    }
    const decoded = jsQR(data, size, size);
    if (!decoded) throw new Error('jsQR 未能解码');
    if (decoded.data !== expected) throw new Error(`解码内容不符：${decoded.data} ≠ ${expected}`);
    console.log(`✅ ${id}.svg 解码成功：内容 "${decoded.data}" === 报名码（${count}×${count} 模块）`);
    pass++;
  } catch (e) {
    console.log(`❌ ${id}.svg 解码失败：${e.message}`);
    fail++;
  }
}
console.log(`\nQR 解码验证：${pass} 通过，${fail} 失败`);
process.exit(fail ? 1 : 0);
