<?php

declare(strict_types=1);

require_once __DIR__ . '/../bootstrap.php';

use App\Framework\Filesystem\FileStorage;
use App\Framework\Queue\FileQueue;
use App\Framework\Queue\ValueObjects\JobPayload;
use App\Framework\Queue\ValueObjects\QueuePriority;
use App\Framework\Serializer\Php\PhpSerializer;

// Simple test job class
class PopDebugJob
{
    public function __construct(
        public string $id,
        public string $message
    ) {
    }
}

echo "🐛 Debug FileQueue Pop Operation\n";
echo "================================\n\n";

// Create temporary queue directory
$queuePath = __DIR__ . '/../tmp/debug_pop_' . uniqid();
mkdir($queuePath, 0777, true);

$storage = new FileStorage();
$queue = new FileQueue($queuePath, storage: $storage);

// Create and push a job
$testJob = new PopDebugJob('pop-debug-1', 'Test pop debug message');
$payload = JobPayload::create($testJob, QueuePriority::normal());

echo "1️⃣ Created payload and pushing...\n";
$queue->push($payload);
echo "2️⃣ Push completed, queue size: " . $queue->size() . "\n";

// Manual debugging of the pop process
$priorityFiles = $queue->getPriorityJobFiles();
echo "3️⃣ Found " . count($priorityFiles) . " priority files\n";

if (! empty($priorityFiles)) {
    $firstFile = reset($priorityFiles);
    echo "4️⃣ First file: " . $firstFile->filename . "\n";

    $priorityDir = $queuePath . '/priority';
    $filePath = $priorityDir . '/' . $firstFile->filename;
    echo "5️⃣ Full file path: {$filePath}\n";

    // Try to read content
    try {
        $content = $storage->get($filePath);
        echo "6️⃣ Read content, length: " . strlen($content) . " bytes\n";

        // Try to unserialize
        $serializer = new PhpSerializer();
        $unserializedPayload = $serializer->deserialize($content);
        echo "7️⃣ Unserialized payload type: " . get_class($unserializedPayload) . "\n";

        if ($unserializedPayload instanceof JobPayload) {
            echo "8️⃣ Payload is JobPayload instance ✅\n";
            echo "9️⃣ Job type: " . get_class($unserializedPayload->job) . "\n";
            echo "🔟 Job ID: " . $unserializedPayload->job->id . "\n";
        } else {
            echo "8️⃣ Payload is NOT JobPayload instance ❌\n";
            echo "   Actual type: " . get_class($unserializedPayload) . "\n";
        }

    } catch (\Throwable $e) {
        echo "6️⃣ Error reading/unserializing: " . $e->getMessage() . "\n";
        echo "   Exception type: " . get_class($e) . "\n";
        echo "   Stack trace:\n" . $e->getTraceAsString() . "\n";
    }
}

// Now try the actual pop
echo "\n🔄 Now trying actual pop...\n";

try {
    $poppedPayload = $queue->pop();
    if ($poppedPayload !== null) {
        echo "1️⃣1️⃣ Pop successful! Job ID: " . $poppedPayload->job->id . "\n";
    } else {
        echo "1️⃣1️⃣ Pop returned null ❌\n";
    }
} catch (\Throwable $e) {
    echo "1️⃣1️⃣ Pop threw exception: " . $e->getMessage() . "\n";
    echo "   Exception type: " . get_class($e) . "\n";
}

echo "1️⃣2️⃣ Final queue size: " . $queue->size() . "\n";

// Cleanup
function deleteDirectory($dir)
{
    if (! is_dir($dir)) {
        return;
    }
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        if (is_dir($path)) {
            deleteDirectory($path);
        } else {
            unlink($path);
        }
    }
    rmdir($dir);
}

deleteDirectory($queuePath);
echo "1️⃣3️⃣ Cleanup completed\n";
