<?php

declare(strict_types=1);

namespace App\Application\Development;

use App\Framework\Attributes\Route;
use App\Framework\Config\Environment;
use App\Framework\Config\EnvKey;
use App\Framework\Development\HotReload\HotReloadServer;
use App\Framework\Http\Method;
use App\Framework\Router\Result\SseResult;

/**
 * Controller for Hot Reload functionality in development
 */
final readonly class HotReloadController
{
    public function __construct(
        private HotReloadServer $hotReloadServer,
        private Environment $environment
    ) {
    }

    /**
     * SSE endpoint for hot reload events
     * Only available in development mode
     */
    #[Route(path: '/dev/hot-reload', method: Method::GET)]
    public function stream(): SseResult
    {
        // Only allow in development
        if (! $this->environment->getBool(EnvKey::APP_DEBUG)) {
            throw new \RuntimeException('Hot Reload is only available in development mode');
        }

        // Temporarily disable deprecation warnings to prevent header issues
        $originalReporting = error_reporting();
        error_reporting(E_ALL & ~E_DEPRECATED);

        // Clear any previous output that might interfere with SSE headers
        if (ob_get_level()) {
            ob_clean();
        }

        return new SseResult(callback: function () use ($originalReporting) {
            try {
                // Start the hot reload server
                $this->hotReloadServer->start();

                // Keep connection alive
                while (connection_aborted() === 0) {
                    sleep(1);
                }

                // Stop when the connection is closed
                $this->hotReloadServer->stop();
            } finally {
                // Restore original error reporting
                error_reporting($originalReporting);
            }
        });
    }
}
