#!/usr/bin/env php
<?php

use App\Framework\CommandBus\CommandBus;
use App\Framework\Console\ConsoleOutput;
use App\Framework\Core\AppBootstrapper;
use App\Framework\Queue\FileQueue;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\MemoryMonitor;

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/src/Framework/Debug/helpers.php';

// Create dependencies for enhanced performance collector
$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();

$queue = $container->get(\App\Framework\Queue\Queue::class);

$worker = new \App\Framework\Worker\Worker(
    $container,
    $queue, #new FileQueue(__DIR__ . '/src/Framework/CommandBus/storage/queue/'),
    $container->get(CommandBus::class),
    $container->get(ConsoleOutput::class),
);

pcntl_signal(SIGTERM, function () use ($worker) {
    $worker->stop();
});

pcntl_signal(SIGINT, function () use ($worker) {
    $worker->stop();
});

$worker->start();



/*
$queue = new FileQueue(__DIR__ . '/src/Framework/CommandBus/storage/queue/');

error_log('Worker started');

error_log(__DIR__ . '/src/Framework/CommandBus/storage/queue');

#$commandBus = $container->get(CommandBus::class);

#$commandBus->dispatch(new \App\Application\Newsletter\SignUp\SignupUserToNewsletter('Michael', 'mail'));

#var_dump($queue);

while (true) {
    $job = $queue->pop();

    if ($job) {
        try {
            // Job verarbeiten

            #$commandBus->handle($job);

            error_log('handled: ' . $job::class);

            #(new JobProcessor())->handle($job);
        } catch (\Throwable $e) {
            // Fehler-Handling / Retry-Logik
        }
    } else {
        // Leerlauf-Pause, z.B. 100 ms
        usleep(100_000);
    }
}*/
