<?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 "=== Verifying Finder Patterns ===\n\n";

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

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

// Expected finder pattern (7x7)
$expectedPattern = [
    [1,1,1,1,1,1,1],
    [1,0,0,0,0,0,1],
    [1,0,1,1,1,0,1],
    [1,0,1,1,1,0,1],
    [1,0,1,1,1,0,1],
    [1,0,0,0,0,0,1],
    [1,1,1,1,1,1,1],
];

$finderLocations = [
    'Top-Left' => [0, 0],
    'Top-Right' => [0, 14],
    'Bottom-Left' => [14, 0],
];

$allCorrect = true;

foreach ($finderLocations as $name => $location) {
    [$startRow, $startCol] = $location;
    echo "{$name} Finder Pattern:\n";
    
    $errors = 0;
    for ($r = 0; $r < 7; $r++) {
        echo "  ";
        for ($c = 0; $c < 7; $c++) {
            $row = $startRow + $r;
            $col = $startCol + $c;
            
            $actual = $matrix->getModuleAt($row, $col)->isDark() ? 1 : 0;
            $expected = $expectedPattern[$r][$c];
            
            if ($actual !== $expected) {
                $errors++;
                echo "X";  // Error
            } else {
                echo ($actual ? "█" : "·");
            }
        }
        echo "\n";
    }
    
    if ($errors === 0) {
        echo "  ✅ Perfect!\n\n";
    } else {
        echo "  ❌ {$errors} errors!\n\n";
        $allCorrect = false;
    }
}

// Check separators (white border around finder patterns)
echo "Checking Separators:\n";

// Top-left separator (row 7, cols 0-7 and col 7, rows 0-7)
$separatorErrors = 0;

// Horizontal separator below top-left finder
for ($c = 0; $c < 8; $c++) {
    if ($matrix->getModuleAt(7, $c)->isDark()) {
        $separatorErrors++;
        echo "  ❌ Position [7,{$c}] should be white (separator)\n";
    }
}

// Vertical separator right of top-left finder  
for ($r = 0; $r < 8; $r++) {
    if ($matrix->getModuleAt($r, 7)->isDark()) {
        $separatorErrors++;
        echo "  ❌ Position [{$r},7] should be white (separator)\n";
    }
}

if ($separatorErrors === 0) {
    echo "  ✅ Top-left separators correct\n";
} else {
    $allCorrect = false;
}

echo "\n";

if ($allCorrect) {
    echo "✅✅✅ ALL FINDER PATTERNS AND SEPARATORS ARE CORRECT! ✅✅✅\n";
} else {
    echo "❌ FINDER PATTERNS HAVE ERRORS!\n";
}

