<?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 "=== Format Information Placement Debug ===\n\n";

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

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

echo "Data: '{$data}'\n";
echo "Matrix Size: {$size}x{$size}\n\n";

// Expected format bits for Mask 5, Level M
$expectedFormatBits = 0b100000011001110;
echo "Expected Format Bits: " . str_pad(decbin($expectedFormatBits), 15, '0', STR_PAD_LEFT) . "\n\n";

// Extract horizontal format info (row 8) with positions
echo "=== Horizontal Format Info (Row 8) ===\n";
echo "Position → Column → Bit\n";

$horizontalBits = '';
$positions = [0, 1, 2, 3, 4, 5, 7, 8, 13, 14, 15, 16, 17, 18, 19, 20];

foreach ($positions as $col) {
    $isDark = $matrix->getModuleAt(8, $col)->isDark();
    $bit = $isDark ? '1' : '0';
    $horizontalBits .= $bit;

    $module = $isDark ? '█' : '░';
    echo sprintf("Col %2d: %s (%s)\n", $col, $module, $bit);
}

echo "\nExtracted bits: {$horizontalBits}\n";

// Now let's see what bits we SHOULD place
echo "\n=== Expected Placement (MSB-first) ===\n";
echo "According to our code:\n";

// Bits 0-5: columns 0-5
for ($i = 0; $i < 6; $i++) {
    $bit = ($expectedFormatBits >> (14 - $i)) & 1;
    echo "Bit {$i}: {$bit} → Col {$i}\n";
}

// Bit 6: column 7
$bit = ($expectedFormatBits >> (14 - 6)) & 1;
echo "Bit 6: {$bit} → Col 7\n";

// Bit 7: column 8
$bit = ($expectedFormatBits >> (14 - 7)) & 1;
echo "Bit 7: {$bit} → Col 8\n";

// Bits 8-14: columns 20 down to 13 (right side)
for ($i = 0; $i < 7; $i++) {
    $bitIndex = 8 + $i;
    $col = $size - 1 - $i; // 20, 19, 18, 17, 16, 15, 14, 13
    $bit = ($expectedFormatBits >> (14 - $bitIndex)) & 1;
    echo "Bit {$bitIndex}: {$bit} → Col {$col}\n";
}

echo "\n=== Comparison ===\n";
$expectedSequence = '';
for ($i = 0; $i < 15; $i++) {
    $expectedSequence .= ($expectedFormatBits >> (14 - $i)) & 1;
}

echo "Expected sequence: {$expectedSequence}\n";
echo "Actual sequence:   {$horizontalBits}\n";
echo ($expectedSequence === $horizontalBits ? "✅ MATCH!" : "❌ MISMATCH!") . "\n";
