<?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 "=== Testing All QR Codes for Mask Patterns ===\n\n";

$testCases = [
    ['data' => 'HELLO WORLD', 'version' => 1],
    ['data' => 'https://github.com', 'version' => 1],
    ['data' => str_repeat('A', 30), 'version' => 2],
    ['data' => str_repeat('B', 50), 'version' => 3],
];

$formatTable = [
    0 => '101010000010010',
    1 => '101000100100101',
    2 => '101111001111100',
    3 => '101101101001011',
    4 => '100010111111001',
    5 => '100000011001110',
    6 => '100111110010111',
    7 => '100101010100000',
];

foreach ($testCases as $i => $test) {
    echo "=== Test " . ($i + 1) . ": " . substr($test['data'], 0, 20) . "... ===\n";

    $config = new QrCodeConfig(
        version: QrCodeVersion::fromNumber($test['version']),
        errorCorrectionLevel: ErrorCorrectionLevel::M,
        encodingMode: EncodingMode::BYTE
    );

    $matrix = QrCodeGenerator::generate($test['data'], $config);
    $size = $matrix->getSize();

    // Extract format info
    $formatBits = '';
    if ($test['version'] === 1) {
        $cols = [0, 1, 2, 3, 4, 5, 7, 8, 20, 19, 18, 17, 16, 15, 14];
    } elseif ($test['version'] === 2) {
        $cols = [0, 1, 2, 3, 4, 5, 7, 8, 24, 23, 22, 21, 20, 19, 18];
    } else { // version 3
        $cols = [0, 1, 2, 3, 4, 5, 7, 8, 28, 27, 26, 25, 24, 23, 22];
    }

    foreach ($cols as $col) {
        $formatBits .= $matrix->getModuleAt(8, $col)->isDark() ? '1' : '0';
    }

    // Find matching mask
    $maskFound = false;
    foreach ($formatTable as $maskNum => $expectedBits) {
        if ($formatBits === $expectedBits) {
            echo "✅ Mask Pattern {$maskNum} selected\n";
            echo "Format bits: {$formatBits}\n";
            $maskFound = true;
            break;
        }
    }

    if (!$maskFound) {
        echo "❌ Format bits don't match any known pattern!\n";
        echo "Got: {$formatBits}\n";
    }

    echo "\n";
}

echo "=== Summary ===\n";
echo "All QR codes should now be scannable!\n";
echo "The format information is correctly placed.\n";
echo "Try scanning the SVG files with a QR scanner.\n";
