<?php

echo "=== Verify Mask Pattern 2 Format Information ===\n\n";

// Format info table from ISO spec
$formatTable = [
    'M' => [
        0 => 0b101010000010010,  // Level M, Mask 0 (Python uses this)
        1 => 0b101000100100101,
        2 => 0b101111001111100,  // Level M, Mask 2 (We use this)
        3 => 0b101101101001011,
        4 => 0b100010111111001,
        5 => 0b100000011001110,
        6 => 0b100111110010111,
        7 => 0b100101010100000,
    ]
];

$ourExpected = $formatTable['M'][2];
$ourBinary = sprintf('%015b', $ourExpected);

echo "Expected Format (M, Mask 2): {$ourBinary}\n";
echo "                              $ourExpected (decimal)\n\n";

// Check what we're actually generating
require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\QrCode\QrCodeGenerator;
use App\Framework\QrCode\ValueObjects\ErrorCorrectionLevel;
use App\Framework\QrCode\ValueObjects\QrCodeConfig;
use App\Framework\QrCode\ValueObjects\QrCodeVersion;
use App\Framework\QrCode\ValueObjects\EncodingMode;

$config = new QrCodeConfig(
    version: QrCodeVersion::fromNumber(1),
    errorCorrectionLevel: ErrorCorrectionLevel::M,
    encodingMode: EncodingMode::BYTE
);

$matrix = QrCodeGenerator::generate("HELLO WORLD", $config);

// Read format info
$formatCols = [0, 1, 2, 3, 4, 5, 7, 8, 20, 19, 18, 17, 16, 15, 14];
$formatH = '';
foreach ($formatCols as $col) {
    $formatH .= $matrix->getModuleAt(8, $col)->isDark() ? '1' : '0';
}

$formatRows = [20, 19, 18, 17, 16, 15, 14, 8, 7, 5, 4, 3, 2, 1, 0];
$formatV = '';
foreach ($formatRows as $row) {
    $formatV .= $matrix->getModuleAt($row, 8)->isDark() ? '1' : '0';
}

echo "Actual Format:\n";
echo "  Horizontal: {$formatH}\n";
echo "  Vertical:   {$formatV}\n";
echo "  H=V: " . ($formatH === $formatV ? "✅" : "❌") . "\n\n";

echo "Comparison:\n";
echo "  Expected: {$ourBinary}\n";
echo "  H actual: {$formatH}\n";
echo "  Match:    " . ($formatH === $ourBinary ? "✅ CORRECT!" : "❌ WRONG!") . "\n\n";

// Decode to verify
$xorMask = "101010000010010";
$unmasked = '';
for ($i = 0; $i < 15; $i++) {
    $unmasked .= (int)$formatH[$i] ^ (int)$xorMask[$i];
}

$ecBits = substr($unmasked, 0, 2);
$maskBits = substr($unmasked, 2, 3);
$ecLevel = match($ecBits) {'01' => 'L', '00' => 'M', '11' => 'Q', '10' => 'H'};
$maskPattern = bindec($maskBits);

echo "Decoded:\n";
echo "  EC Level: {$ecLevel} (expected: M)\n";
echo "  Mask Pattern: {$maskPattern} (expected: 2)\n\n";

if ($ecLevel === 'M' && $maskPattern === 2 && $formatH === $formatV) {
    echo "✅✅✅ FORMAT INFORMATION IS PERFECT! ✅✅✅\n";
    echo "The QR code should be scannable if the mask is applied correctly!\n";
} else {
    echo "❌ FORMAT INFORMATION HAS ERRORS!\n";
}

