<?php

declare(strict_types=1);

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

use App\Framework\Core\AppBootstrapper;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Http\Method;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\Performance\MemoryMonitor;
use App\Framework\Router\CompiledRoutes;

echo "=== Campaign Route Debug ===" . PHP_EOL . PHP_EOL;

// Bootstrap application like in public/index.php
$basePath = dirname(__DIR__, 2);
$clock = new SystemClock();
$highResClock = new SystemHighResolutionClock();
$memoryMonitor = new MemoryMonitor();
$collector = new EnhancedPerformanceCollector($clock, $highResClock, $memoryMonitor, enabled: true);
$bootstrapper = new AppBootstrapper($basePath, $collector, $memoryMonitor);
$app = $bootstrapper->bootstrapWeb();

// Get container
$container = $app->getContainer();

/** @var CompiledRoutes $compiledRoutes */
$compiledRoutes = $container->get(CompiledRoutes::class);

// Get all dynamic routes for GET method with 'default' subdomain
$pattern = $compiledRoutes->getCompiledPattern(Method::GET, 'default');

if (! $pattern) {
    echo "❌ No compiled pattern found for GET default" . PHP_EOL;
    exit(1);
}

echo "✅ Found compiled pattern" . PHP_EOL;
echo "Regex: " . $pattern->regex . PHP_EOL . PHP_EOL;
echo "Number of routes: " . count($pattern->routes) . PHP_EOL . PHP_EOL;

// Search for campaign routes
echo "=== Campaign Routes ===" . PHP_EOL;
$found = false;

foreach ($pattern->routes as $i => $routeData) {
    if (str_contains($routeData->route->path, 'campaign')) {
        $found = true;
        echo "Route $i:" . PHP_EOL;
        echo "  Path: " . $routeData->route->path . PHP_EOL;
        echo "  Controller: " . $routeData->route->controller . PHP_EOL;
        echo "  Action: " . $routeData->route->action . PHP_EOL;
        echo "  Regex: " . $routeData->route->regex . PHP_EOL;
        echo PHP_EOL;
    }
}

if (! $found) {
    echo "❌ No campaign routes found in compiled routes!" . PHP_EOL;
} else {
    echo "✅ Campaign routes found" . PHP_EOL;
}

// Test the specific path
echo PHP_EOL . "=== Testing Path ===" . PHP_EOL;
$testPath = '/campaign/test-campaign/presave/spotify';
echo "Path: $testPath" . PHP_EOL;

if (preg_match($pattern->regex, $testPath, $matches)) {
    echo "✅ Path matches compiled regex!" . PHP_EOL;
    echo "Matches: " . print_r($matches, true) . PHP_EOL;
} else {
    echo "❌ Path does NOT match compiled regex" . PHP_EOL;
}
