<?php

declare(strict_types=1);

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

use App\Framework\Cache\Cache;
use App\Framework\Cache\Driver\InMemoryCache;
use App\Framework\Cache\GeneralCache;
use App\Framework\Context\ContextType;
use App\Framework\Core\PathProvider;
use App\Framework\DateTime\Clock;
use App\Framework\DateTime\SystemClock;
use App\Framework\DI\DefaultContainer;
use App\Framework\Discovery\DiscoveryServiceBootstrapper;
use App\Framework\Mcp\Tools\CodebaseAnalyzer;
use App\Framework\Serializer\Php\PhpSerializer;
use App\Framework\Serializer\Php\PhpSerializerConfig;

echo "=== CodebaseAnalyzer MCP Tool Test ===\n\n";

try {
    // Setup container and dependencies
    $container = new DefaultContainer();
    $cacheDriver = new InMemoryCache();
    $serializer = new PhpSerializer(PhpSerializerConfig::safe());
    $cache = new GeneralCache($cacheDriver, $serializer);
    $clock = new SystemClock();
    $basePath = file_exists('/var/www/html/src') ? '/var/www/html' : __DIR__ . '/../..';
    $pathProvider = new PathProvider($basePath);

    // Register core dependencies
    $container->singleton(Cache::class, $cache);
    $container->singleton(Clock::class, $clock);
    $container->singleton(PathProvider::class, $pathProvider);
    $container->singleton(ContextType::class, ContextType::CLI_SCRIPT);

    // Clear opcache to avoid issues with cached broken files
    if (function_exists('opcache_reset')) {
        opcache_reset();
    }

    // Bootstrap discovery system
    $discoveryBootstrapper = new DiscoveryServiceBootstrapper($container, $clock);
    $discoveryBootstrapper->bootstrap();

    echo "✅ Discovery system bootstrapped\n";

    // Get CodebaseAnalyzer
    $analyzer = $container->get(CodebaseAnalyzer::class);

    echo "✅ CodebaseAnalyzer successfully retrieved from container\n\n";

    // Test 1: Find Controllers
    echo "--- Test 1: Find Controllers ---\n";
    $controllers = $analyzer->findControllers();
    echo "Found Controllers: " . $controllers['total_controllers'] . "\n";
    echo "Found Routes: " . $controllers['total_routes'] . "\n";
    if (! empty($controllers['controllers'])) {
        echo "Example Controller: " . $controllers['controllers'][0]['class_name'] . "\n";
    }
    echo "\n";

    // Test 2: Find Services
    echo "--- Test 2: Find Services ---\n";
    $services = $analyzer->findServices();
    echo "Found Services: " . $services['total'] . "\n";
    if (! empty($services['services'])) {
        echo "Example Service: " . $services['services'][0]['class_name'] . "\n";
    }
    echo "\n";

    // Test 3: Find Value Objects
    echo "--- Test 3: Find Value Objects ---\n";
    $valueObjects = $analyzer->findValueObjects();
    echo "Found Value Objects: " . $valueObjects['total'] . "\n";
    if (! empty($valueObjects['value_objects'])) {
        echo "Example VO: " . $valueObjects['value_objects'][0]['class_name'] . "\n";
    }
    echo "\n";

    // Test 4: Find Initializers
    echo "--- Test 4: Find Initializers ---\n";
    $initializers = $analyzer->findInitializers();
    echo "Found Initializers: " . $initializers['total'] . "\n";
    if (! empty($initializers['initializers'])) {
        echo "Example Initializer: " . $initializers['initializers'][0]['class_name'] . "\n";
        echo "Return Type: " . ($initializers['initializers'][0]['return_type'] ?? 'unknown') . "\n";
    }
    echo "\n";

    // Test 5: Find MCP Tools
    echo "--- Test 5: Find MCP Tools ---\n";
    $mcpTools = $analyzer->findMcpTools();
    echo "Found MCP Tools: " . $mcpTools['total'] . "\n";
    if (! empty($mcpTools['mcp_tools'])) {
        foreach (array_slice($mcpTools['mcp_tools'], 0, 5) as $tool) {
            echo "  - {$tool['name']}: {$tool['description']}\n";
        }
    }
    echo "\n";

    // Test 6: Search by Pattern
    echo "--- Test 6: Search by Pattern (*Repository) ---\n";
    $repositories = $analyzer->searchByPattern('*Repository');
    echo "Found components matching '*Repository': " . $repositories['total'] . "\n";
    if (! empty($repositories['results'])) {
        foreach (array_slice($repositories['results'], 0, 3) as $result) {
            echo "  - {$result['type']}: {$result['data']['class_name']}\n";
        }
    }
    echo "\n";

    // Test 7: Custom Query
    echo "--- Test 7: Custom Query (Controllers + Initializers) ---\n";
    $customResult = $analyzer->analyzeCodebase([
        'attribute_types' => [
            'App\Framework\Attributes\Route',
            'App\Framework\Attributes\Initializer',
        ],
        'max_results' => 5,
    ]);

    echo "Execution Time: {$customResult['execution_time_ms']}ms\n";
    echo "Total Routes: " . count($customResult['routes']) . "\n";
    echo "Total Initializers: " . count($customResult['initializers']) . "\n";
    echo "\n";

    echo "=== All Tests Completed Successfully ✅ ===\n";

} catch (\Throwable $e) {
    echo "❌ Error: {$e->getMessage()}\n";
    echo "File: {$e->getFile()}:{$e->getLine()}\n";
    echo "\nStack Trace:\n";
    echo $e->getTraceAsString();
    exit(1);
}
