<?php

declare(strict_types=1);

namespace App\Framework\Router;

use App\Framework\Attributes\Route;
use App\Framework\Context\ContextType;
use App\Framework\Core\PathProvider;
use App\Framework\Core\RouteCache;
use App\Framework\Core\RouteCompiler;
use App\Framework\DI\Container;
use App\Framework\DI\DefaultContainer;
use App\Framework\DI\Initializer;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\Http\Method;

/**
 * Verantwortlich für die Einrichtung des Routers
 */
final readonly class RouterSetup
{
    public function __construct(
        private Container $container,
        private RouteCompiler    $routeCompiler,
        private DiscoveryRegistry $results,
    ) {}

    /**
     * Richtet den Router basierend auf den verarbeiteten Attributen ein
     * Nur für Web-Context - CLI braucht keine HTTP-Routes
     */
    #[Initializer(ContextType::WEB)]
    public function __invoke(): Router
    {
        #$routeCache = new RouteCache($this->pathProvider->getCachePath('routes.cache.php'));

        $routeCount = $this->results->attributes->getCount(Route::class);
        error_log("🚦 ROUTER SETUP: Route count from discovery = {$routeCount}");

        if ($routeCount > 0) {
            $discoveredRoutes = $this->results->attributes->get(Route::class);

            // Direct DiscoveredAttribute API
            error_log("🚦 ROUTER SETUP: About to compile routes");
            try {
                $optimizedRoutes = $this->routeCompiler->compileOptimized(...$discoveredRoutes);
                error_log("🚦 ROUTER SETUP: Routes compiled successfully");
            } catch (\Throwable $e) {
                error_log("🚦 ROUTER SETUP: ERROR compiling routes: " . $e->getMessage());
                error_log("🚦 ROUTER SETUP: Exception trace: " . $e->getTraceAsString());
                throw $e;
            }

            // DEBUG: Log available static routes structure
            error_log("🚦 ROUTER SETUP: About to analyze route structure");
            $staticRoutes = $optimizedRoutes->getStaticRoutes();
            error_log("🚦 ROUTER SETUP: HTTP Methods count = " . count($staticRoutes));

            // Check GET method subdomain keys
            $getSubdomainKeys = $optimizedRoutes->getSubdomainKeys(Method::GET);
            error_log("🚦 ROUTER SETUP: GET method has subdomain keys: " . json_encode($getSubdomainKeys));

            // Log routes per subdomain for GET
            foreach ($getSubdomainKeys as $subdomainKey) {
                $routes = $optimizedRoutes->getStaticRoutesForSubdomain(Method::GET, $subdomainKey);
                error_log("🚦 ROUTER SETUP: GET subdomain '{$subdomainKey}' has " . count($routes) . " routes");
                foreach ($routes as $path => $route) {
                    error_log("🚦 ROUTER SETUP:   - {$path}");
                }
            }

            // Cache speichern
            #$routeCache->save($optimizedRoutes);

        } else {
            $optimizedRoutes = $this->routeCompiler->compileOptimized();
        }

        $router = new HttpRouter($optimizedRoutes);

        $this->container->bind(CompiledRoutes::class, $optimizedRoutes);
        $this->container->bind(HttpRouter::class, $router);
        $this->container->bind(Router::class, $router); // Interface binding

        return $router;
    }
}
