<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\QrCode\ValueObjects\QrCodeMatrix;
use App\Framework\QrCode\ValueObjects\QrCodeVersion;
use App\Framework\QrCode\ValueObjects\ErrorCorrectionLevel;
use App\Framework\QrCode\Structure\FormatInformation;
use App\Framework\QrCode\ValueObjects\Module;

echo "=== Direct Format Information Placement Test ===\n\n";

// Create empty matrix
$version = QrCodeVersion::fromNumber(1);
$matrix = QrCodeMatrix::create($version);
$size = $matrix->getSize();

echo "Empty Matrix Size: {$size}x{$size}\n\n";

// Apply format information for Mask 5, Level M
$level = ErrorCorrectionLevel::M;
$maskPattern = 5;

echo "Applying Format Info: Level M, Mask 5\n";
echo "Expected bits: 100000011001110\n\n";

$matrix = FormatInformation::apply($matrix, $level, $maskPattern);

// Extract horizontal format info
echo "=== Horizontal (Row 8) ===\n";
$horizontalBits = '';
// Left side: cols 0-5, 7-8 (8 bits, skip 6)
// Right side: cols 20-14 (7 bits, NO skip!)
$cols = [0, 1, 2, 3, 4, 5, 7, 8, 20, 19, 18, 17, 16, 15, 14];

foreach ($cols 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 "\nCombined: {$horizontalBits}\n";
echo "Expected: 100000011001110\n";
echo ($horizontalBits === '100000011001110' ? "✅ MATCH!" : "❌ MISMATCH!") . "\n";

// Extract vertical format info
echo "\n=== Vertical (Column 8) ===\n";
$verticalBits = '';
// According to ISO spec:
// Bits 0-6: rows from BOTTOM (20, 19, 18, 17, 16, 15, 14)
// Bits 7-14: rows from TOP (8, 7, 5, 4, 3, 2, 1, 0) - skip row 6
$rows = [20, 19, 18, 17, 16, 15, 14, 8, 7, 5, 4, 3, 2, 1, 0];

foreach ($rows as $row) {
    $isDark = $matrix->getModuleAt($row, 8)->isDark();
    $bit = $isDark ? '1' : '0';
    $verticalBits .= $bit;

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

echo "\nCombined: {$verticalBits}\n";
echo "Expected: 100000011001110\n";
echo ($verticalBits === '100000011001110' ? "✅ MATCH!" : "❌ MISMATCH!") . "\n";

// Debug: Show exact bit extraction
echo "\n=== Bit Extraction Debug ===\n";
$formatBits = 0b100000011001110;

echo "Format bits value: {$formatBits} (decimal: " . $formatBits . ")\n";
echo "Binary: " . str_pad(decbin($formatBits), 15, '0', STR_PAD_LEFT) . "\n\n";

echo "MSB-first extraction (14 - i):\n";
for ($i = 0; $i < 15; $i++) {
    $bit = ($formatBits >> (14 - $i)) & 1;
    echo "Bit {$i}: {$bit}\n";
}
