<?php

declare(strict_types=1);

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

use App\Framework\QrCode\Masking\MaskPattern;
use App\Framework\QrCode\ValueObjects\Module;
use App\Framework\QrCode\ValueObjects\QrCodeMatrix;

echo "=== Testing Mask Pattern 2 Application ===\n\n";

// Mask Pattern 2: (row + column) % 3 == 0
echo "Mask Pattern 2 formula: (row + column) % 3 == 0\n\n";

$pattern = MaskPattern::PATTERN_2;

// Test a few positions
$testPositions = [
    [0, 0],  // 0+0=0, 0%3=0 → should invert
    [0, 1],  // 0+1=1, 1%3=1 → should NOT invert
    [0, 2],  // 0+2=2, 2%3=2 → should NOT invert
    [1, 2],  // 1+2=3, 3%3=0 → should invert
    [10, 11], // 10+11=21, 21%3=0 → should invert
    [10, 12], // 10+12=22, 22%3=1 → should NOT invert
];

echo "Testing shouldInvert() at various positions:\n";
foreach ($testPositions as [$row, $col]) {
    $sum = $row + $col;
    $mod = $sum % 3;
    $shouldInvert = $pattern->shouldInvert($row, $col);
    $expected = ($mod === 0);
    $match = $shouldInvert === $expected ? "✅" : "❌";
    
    echo sprintf(
        "  (%2d,%2d): sum=%2d, mod=%d, shouldInvert=%s, expected=%s %s\n",
        $row, $col, $sum, $mod,
        $shouldInvert ? 'true ' : 'false',
        $expected ? 'true ' : 'false',
        $match
    );
}

echo "\n";

// Test actual mask application
echo "Testing actual mask application on a small matrix:\n";

$matrix = new QrCodeMatrix(5);
// Set all modules to light initially
for ($r = 0; $r < 5; $r++) {
    for ($c = 0; $c < 5; $c++) {
        $matrix = $matrix->setModuleAt($r, $c, Module::light());
    }
}

// Now apply mask to check which modules get inverted
for ($r = 0; $r < 5; $r++) {
    for ($c = 0; $c < 5; $c++) {
        if ($pattern->shouldInvert($r, $c)) {
            $matrix = $matrix->setModuleAt($r, $c, Module::dark());
        }
    }
}

// Display result
echo "Mask pattern (1 = inverted, 0 = not inverted):\n";
for ($r = 0; $r < 5; $r++) {
    echo "  ";
    for ($c = 0; $c < 5; $c++) {
        echo $matrix->getModuleAt($r, $c)->isDark() ? '1' : '0';
    }
    echo "\n";
}

echo "\nExpected pattern:\n";
echo "  10010\n";
echo "  01001\n";
echo "  00100\n";
echo "  10010\n";
echo "  01001\n";

