<?php

declare(strict_types=1);

namespace App\Framework\Router;

use App\Framework\Attributes\Route;
use App\Framework\Context\ContextType;
use App\Framework\Core\RouteCompiler;
use App\Framework\DI\Initializer;
use App\Framework\Discovery\Results\DiscoveryRegistry;

/**
 * Route Compiler Initializer - Kompiliert entdeckte Routen für Web-Context
 */
final readonly class RouteCompilerInitializer
{
    public function __construct(
        private DiscoveryRegistry $discoveryRegistry,
        private RouteCompiler $routeCompiler
    ) {
    }

    #[Initializer(ContextType::WEB)]
    public function __invoke(): CompiledRoutes
    {
        error_log("RouteCompilerInitializer: Starting route compilation");

        try {
            // Hole Route-Attribute aus Discovery Registry
            error_log("RouteCompilerInitializer: About to access discoveryRegistry->attributes");
            $routeAttributes = $this->discoveryRegistry->attributes->get(Route::class);
            error_log("RouteCompilerInitializer: Successfully got " . count($routeAttributes) . " route attributes");

            if (empty($routeAttributes)) {
                error_log("RouteCompilerInitializer: No routes found, returning empty CompiledRoutes");

                return new CompiledRoutes([], [], []);
            }

            // Kompiliere die Routen
            error_log("RouteCompilerInitializer: About to compile routes");
            $compiledData = $this->routeCompiler->compile(...$routeAttributes);
            error_log("RouteCompilerInitializer: Successfully compiled " . count($compiledData) . " route groups");

            // Extrahiere Arrays aus kompilierten Daten
            $staticRoutes = [];
            $dynamicRoutes = [];
            $namedRoutes = [];

            foreach ($compiledData as $subdomain => $methods) {
                foreach ($methods as $method => $routes) {
                    $staticRoutes[$subdomain][$method] = $routes['static'] ?? [];
                    $dynamicRoutes[$subdomain][$method] = $routes['dynamic'] ?? [];

                    // Named routes extrahieren
                    foreach (array_merge($routes['static'] ?? [], $routes['dynamic'] ?? []) as $route) {
                        if (isset($route->name) && $route->name !== null) {
                            $namedRoutes[$route->name] = $route;
                        }
                    }
                }
            }

            error_log("RouteCompilerInitializer: Created CompiledRoutes with " .
                     count($staticRoutes) . " static and " . count($dynamicRoutes) . " dynamic route groups");

            $result = new CompiledRoutes($staticRoutes, $dynamicRoutes, $namedRoutes);
            error_log("RouteCompilerInitializer: Successfully created CompiledRoutes object");

            return $result;

        } catch (\Throwable $e) {
            error_log("RouteCompilerInitializer: ERROR - " . $e->getMessage());
            error_log("RouteCompilerInitializer: ERROR - Stack trace: " . $e->getTraceAsString());

            // Return empty routes on error
            return new CompiledRoutes([], [], []);
        }
    }
}
