<?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;

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

echo "🐛 Debug FileQueue Step by Step\n";
echo "==============================\n\n";

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

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

echo "1️⃣ Queue created, path: {$queuePath}\n";

// Check if directories were created
$priorityDir = $queuePath . '/priority';
$delayedDir = $queuePath . '/delayed';

echo "2️⃣ Priority dir exists: " . (is_dir($priorityDir) ? "✅" : "❌") . "\n";
echo "3️⃣ Delayed dir exists: " . (is_dir($delayedDir) ? "✅" : "❌") . "\n";

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

echo "4️⃣ Created payload with job ID: {$testJob->id}\n";

// Push the job
try {
    $queue->push($payload);
    echo "5️⃣ Push completed successfully\n";
} catch (\Throwable $e) {
    echo "5️⃣ Push failed: " . $e->getMessage() . "\n";
    exit(1);
}

// Check queue size
$size = $queue->size();
echo "6️⃣ Queue size after push: {$size}\n";

// Check what files exist
$priorityFiles = $queue->getPriorityJobFiles();
echo "7️⃣ Priority files count: " . count($priorityFiles) . "\n";

if (! empty($priorityFiles)) {
    echo "8️⃣ First file: " . $priorityFiles[0]->filename . "\n";

    // Try to read the file manually
    $filePath = $priorityDir . '/' . $priorityFiles[0]->filename;
    echo "9️⃣ File path: {$filePath}\n";
    echo "🔟 File exists: " . (file_exists($filePath) ? "✅" : "❌") . "\n";

    if (file_exists($filePath)) {
        $content = file_get_contents($filePath);
        echo "1️⃣1️⃣ File content length: " . strlen($content) . " bytes\n";
        echo "1️⃣2️⃣ Content preview: " . substr($content, 0, 100) . "...\n";
    }
}

// Try to pop
echo "\n🔄 Attempting to pop...\n";

try {
    $poppedPayload = $queue->pop();
    if ($poppedPayload !== null) {
        echo "1️⃣3️⃣ Pop successful! Job ID: " . $poppedPayload->job->id . "\n";
    } else {
        echo "1️⃣3️⃣ Pop returned null\n";
    }
} catch (\Throwable $e) {
    echo "1️⃣3️⃣ Pop failed: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
}

// Final queue size
$finalSize = $queue->size();
echo "1️⃣4️⃣ Final queue size: {$finalSize}\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️⃣5️⃣ Cleanup completed\n";
