<?php

declare(strict_types=1);

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;

echo "=== Which Mask Pattern Was Selected? ===\n\n";

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

$matrix = QrCodeGenerator::generate($data, $config);

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

echo "Extracted format bits: {$formatBits}\n\n";

// Try to match with known formats for Level M
$formatTable = [
    0 => '101010000010010',
    1 => '101000100100101',
    2 => '101111001111100',
    3 => '101101101001011',
    4 => '100010111111001',
    5 => '100000011001110',
    6 => '100111110010111',
    7 => '100101010100000',
];

foreach ($formatTable as $maskNum => $expectedBits) {
    if ($formatBits === $expectedBits) {
        echo "✅ MATCH! Mask Pattern: {$maskNum}\n";
        echo "Format bits: {$expectedBits}\n";
        return;
    }
}

echo "❌ No exact match found!\n\n";
echo "Closest matches:\n";
foreach ($formatTable as $maskNum => $expectedBits) {
    $diff = 0;
    for ($i = 0; $i < 15; $i++) {
        if ($formatBits[$i] !== $expectedBits[$i]) {
            $diff++;
        }
    }
    echo "Mask {$maskNum}: {$diff} bits different\n";
}
