<?php

declare(strict_types=1);

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

use App\Framework\Core\AppBootstrapper;
use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\Performance\MemoryMonitor;
use App\Framework\Scheduler\Schedules\CronSchedule;
use App\Framework\Scheduler\Schedules\IntervalSchedule;
use App\Framework\Scheduler\Schedules\OneTimeSchedule;
use App\Framework\Scheduler\Services\SchedulerService;

echo "🕐 Testing Scheduler System\n";
echo "===========================\n\n";

try {
    // Bootstrap framework
    $clock = new SystemClock();
    $highResClock = new SystemHighResolutionClock();
    $memoryMonitor = new MemoryMonitor();
    $collector = new EnhancedPerformanceCollector($clock, $highResClock, $memoryMonitor, enabled: false);

    $bootstrapper = new AppBootstrapper(__DIR__ . '/../..', $collector, $memoryMonitor);
    $container = $bootstrapper->bootstrapWorker();

    $scheduler = $container->get(SchedulerService::class);

    echo "✅ Framework bootstrapped successfully\n";
    echo "✅ SchedulerService retrieved\n\n";

    // Test 1: Schedule a task with cron expression
    echo "📋 Test 1: Scheduling a cron task (every minute)\n";
    echo "------------------------------------------------\n";

    $cronSchedule = CronSchedule::fromExpression('* * * * *'); // Every minute
    $scheduler->schedule('cleanup-task', $cronSchedule, function () {
        echo "🧹 Running cleanup task at " . date('Y-m-d H:i:s') . "\n";

        return ['status' => 'cleaned', 'files_removed' => 42];
    });

    echo "✅ Cron task scheduled successfully\n\n";

    // Test 2: Schedule an interval task
    echo "📋 Test 2: Scheduling an interval task (every 30 seconds)\n";
    echo "---------------------------------------------------------\n";

    $intervalSchedule = IntervalSchedule::every(Duration::fromSeconds(30));
    $scheduler->schedule('heartbeat-task', $intervalSchedule, function () {
        echo "💓 Heartbeat at " . date('Y-m-d H:i:s') . "\n";

        return ['status' => 'alive', 'timestamp' => time()];
    });

    echo "✅ Interval task scheduled successfully\n\n";

    // Test 3: Schedule a one-time task
    echo "📋 Test 3: Scheduling a one-time task (in 5 seconds)\n";
    echo "----------------------------------------------------\n";

    $oneTimeSchedule = OneTimeSchedule::at(Timestamp::fromFloat(time() + 5));
    $scheduler->schedule('welcome-task', $oneTimeSchedule, function () {
        echo "👋 Welcome task executed at " . date('Y-m-d H:i:s') . "\n";

        return ['status' => 'welcomed', 'message' => 'Hello World!'];
    });

    echo "✅ One-time task scheduled successfully\n\n";

    // Test 4: Check scheduled tasks
    echo "📋 Test 4: Checking scheduled tasks\n";
    echo "-----------------------------------\n";

    $tasks = $scheduler->getScheduledTasks();
    echo "📊 Total scheduled tasks: " . count($tasks) . "\n";

    foreach ($tasks as $taskId => $task) {
        echo "  • Task: $taskId\n";
        echo "    Type: " . $task->schedule->getType() . "\n";
        echo "    Description: " . $task->schedule->getDescription() . "\n";
        echo "    Next execution: " . ($task->nextExecution ? $task->nextExecution->format('c') : 'N/A') . "\n";
        echo "\n";
    }

    // Test 5: Check due tasks
    echo "📋 Test 5: Checking due tasks\n";
    echo "-----------------------------\n";

    $dueTasks = $scheduler->getDueTasks();
    echo "📊 Due tasks: " . count($dueTasks) . "\n";

    if (count($dueTasks) > 0) {
        foreach ($dueTasks as $task) {
            echo "  • Due task: {$task->id}\n";
        }
    } else {
        echo "  ℹ️  No tasks are due for execution right now\n";
    }
    echo "\n";

    // Test 6: Get scheduler statistics
    echo "📋 Test 6: Scheduler statistics\n";
    echo "-------------------------------\n";

    $stats = $scheduler->getStats();
    echo "📊 Scheduler Statistics:\n";
    echo "  • Total tasks: {$stats['total_tasks']}\n";
    echo "  • Due tasks: {$stats['due_tasks']}\n";
    echo "  • Next execution: " . ($stats['next_execution'] ?? 'N/A') . "\n";
    echo "  • Schedule types:\n";
    foreach ($stats['schedule_types'] as $type => $count) {
        echo "    - $type: $count\n";
    }
    echo "\n";

    // Test 7: Execute due tasks (if any)
    echo "📋 Test 7: Executing due tasks\n";
    echo "------------------------------\n";

    $results = $scheduler->executeDueTasks();
    if (count($results) > 0) {
        echo "✅ Executed " . count($results) . " tasks:\n";
        foreach ($results as $result) {
            echo "  • Task: {$result->taskId}\n";
            echo "    Success: " . ($result->success ? 'Yes' : 'No') . "\n";
            echo "    Execution time: {$result->executionTimeSeconds}s\n";
            if ($result->result) {
                echo "    Result: " . json_encode($result->result) . "\n";
            }
            if ($result->error) {
                echo "    Error: " . $result->error->getMessage() . "\n";
            }
            echo "\n";
        }
    } else {
        echo "ℹ️  No tasks were due for execution\n\n";
    }

    echo "📊 Test Results:\n";
    echo "===============\n";
    echo "✅ Scheduler system is working correctly\n";
    echo "✅ Different schedule types can be created\n";
    echo "✅ Tasks can be scheduled and tracked\n";
    echo "✅ Due task detection works\n";
    echo "✅ Task execution system functional\n";
    echo "✅ Statistics and monitoring available\n";

} catch (Exception $e) {
    echo "❌ Test failed: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}

echo "\n🎉 Scheduler system test completed successfully!\n";
