<?php

declare(strict_types=1);

namespace App\Framework\Mcp\Tools\Categories\Development;

use App\Framework\DI\Container;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\Discovery\UnifiedDiscoveryService;
use App\Framework\Mcp\Core\McpToolContext;
use App\Framework\Mcp\McpTool;
use App\Framework\Mcp\ValueObjects\OutputFormat;
use App\Framework\Router\CompiledRoutes;

/**
 * Framework Analysis and Introspection Tools
 *
 * Provides comprehensive analysis capabilities for the Custom PHP Framework,
 * including route inspection, container analysis, attribute discovery,
 * health monitoring, and architectural insights.
 */
final readonly class FrameworkTools
{
    public function __construct(
        private McpToolContext $context,
        private Container $container,
        private UnifiedDiscoveryService $discoveryService,
        private CompiledRoutes $compiledRoutes,
        private DiscoveryRegistry $discoveryRegistry
    ) {
    }

    #[McpTool(
        name: 'analyze_routes',
        description: 'Comprehensive route analysis with security insights, performance metrics, and architectural guidance',
        category: 'development',
        tags: ['routing', 'analysis', 'architecture'],
        cacheable: true,
        defaultCacheTtl: 300
    )]
    public function analyzeRoutes(
        ?string $controller = null,
        ?string $method = null,
        bool $includeMetrics = true,
        OutputFormat $format = OutputFormat::ARRAY
    ): mixed {
        $cacheKey = "routes_analysis_" . md5(($controller ?? '') . ($method ?? '') . ($includeMetrics ? '1' : '0'));

        $result = $this->context->cache->remember($cacheKey, function () use ($controller, $method, $includeMetrics) {
            // Compiled routes analysis (web context)
            $compiledData = $this->analyzeCompiledRoutes($controller, $method);

            // Discovered routes analysis (CLI/MCP context)
            $discoveredData = $this->analyzeDiscoveredRoutes($controller, $method);

            // Route quality analysis
            $qualityAnalysis = $this->analyzeRouteQuality($compiledData['routes'], $discoveredData['routes']);

            // Security analysis
            $securityAnalysis = $this->analyzeRouteSecurity($compiledData['routes'], $discoveredData['routes']);

            // Performance insights
            $performanceInsights = $includeMetrics ? $this->analyzeRoutePerformance($compiledData['routes']) : null;

            // Architectural patterns
            $architecturalPatterns = $this->analyzeRouteArchitecture($compiledData['routes'], $discoveredData['routes']);

            $totalRoutes = $compiledData['total'] + $discoveredData['total'];

            return [
                'summary' => [
                    'total_routes' => $totalRoutes,
                    'compiled_routes' => $compiledData['total'],
                    'discovered_routes' => $discoveredData['total'],
                    'context' => $compiledData['total'] > 0 ? 'web' : 'cli/mcp',
                    'health_score' => $this->calculateRouteHealthScore($qualityAnalysis, $securityAnalysis),
                    'timestamp' => date('Y-m-d H:i:s'),
                ],
                'compiled_routes' => $compiledData,
                'discovered_routes' => $discoveredData,
                'quality_analysis' => $qualityAnalysis,
                'security_analysis' => $securityAnalysis,
                'performance_insights' => $performanceInsights,
                'architectural_patterns' => $architecturalPatterns,
                'recommendations' => $this->generateRouteRecommendations(
                    $qualityAnalysis,
                    $securityAnalysis,
                    $architecturalPatterns
                ),
            ];
        }, 300);

        return $this->context->formatOutput($result, $format);
    }

    #[McpTool(
        name: 'analyze_container_bindings',
        description: 'Advanced DI container analysis with dependency mapping, circular dependency detection, and optimization insights',
        category: 'development',
        tags: ['dependency-injection', 'container', 'architecture'],
        cacheable: true,
        defaultCacheTtl: 600
    )]
    public function analyzeContainerBindings(
        ?string $service = null,
        bool $includeDependencyGraph = true,
        bool $detectCircularDependencies = true,
        OutputFormat $format = OutputFormat::ARRAY
    ): mixed {
        $cacheKey = "container_analysis_" . md5(($service ?? '') . ($includeDependencyGraph ? '1' : '0'));

        $result = $this->context->cache->remember($cacheKey, function () use ($service, $includeDependencyGraph, $detectCircularDependencies) {
            // Container introspection
            $bindings = $this->extractContainerBindings($service);

            // Dependency graph analysis
            $dependencyGraph = $includeDependencyGraph ? $this->buildDependencyGraph($bindings) : null;

            // Circular dependency detection
            $circularDependencies = $detectCircularDependencies ? $this->detectCircularDependencies($dependencyGraph) : [];

            // Service lifecycle analysis
            $lifecycleAnalysis = $this->analyzeServiceLifecycle($bindings);

            // Memory and performance analysis
            $performanceAnalysis = $this->analyzeContainerPerformance($bindings);

            // Architecture compliance
            $complianceAnalysis = $this->analyzeContainerCompliance($bindings);

            return [
                'summary' => [
                    'total_bindings' => count($bindings),
                    'singletons' => $lifecycleAnalysis['singletons'],
                    'transients' => $lifecycleAnalysis['transients'],
                    'circular_dependencies' => count($circularDependencies),
                    'health_score' => $this->calculateContainerHealthScore($circularDependencies, $complianceAnalysis),
                    'timestamp' => date('Y-m-d H:i:s'),
                ],
                'bindings' => $bindings,
                'dependency_graph' => $dependencyGraph,
                'circular_dependencies' => $circularDependencies,
                'lifecycle_analysis' => $lifecycleAnalysis,
                'performance_analysis' => $performanceAnalysis,
                'compliance_analysis' => $complianceAnalysis,
                'recommendations' => $this->generateContainerRecommendations(
                    $circularDependencies,
                    $performanceAnalysis,
                    $complianceAnalysis
                ),
            ];
        }, 600);

        return $this->context->formatOutput($result, $format);
    }

    #[McpTool(
        name: 'discover_attributes',
        description: 'Advanced attribute discovery with usage patterns, validation, and architectural insights',
        category: 'development',
        tags: ['attributes', 'discovery', 'reflection'],
        cacheable: true,
        defaultCacheTtl: 300
    )]
    public function discoverAttributes(
        string $attributeClass,
        ?string $targetClass = null,
        bool $includeUsagePatterns = true,
        bool $validateAttributes = true,
        OutputFormat $format = OutputFormat::ARRAY
    ): mixed {
        $cacheKey = "attributes_" . md5($attributeClass . ($targetClass ?? '') . ($includeUsagePatterns ? '1' : '0'));

        $result = $this->context->cache->remember($cacheKey, function () use ($attributeClass, $targetClass, $includeUsagePatterns, $validateAttributes) {
            try {
                // Discover attributes
                $discoveryRegistry = $this->discoveryService->discover();
                $attributes = $discoveryRegistry->attributes->get($attributeClass);

                // Filter by target class if specified
                if ($targetClass) {
                    $attributes = array_filter(
                        $attributes,
                        fn ($attr) =>
                        ($attr->additionalData['class'] ?? '') === $targetClass
                    );
                }

                // Usage pattern analysis
                $usagePatterns = $includeUsagePatterns ? $this->analyzeAttributeUsagePatterns($attributes, $attributeClass) : null;

                // Attribute validation
                $validationResults = $validateAttributes ? $this->validateAttributes($attributes, $attributeClass) : null;

                // Coverage analysis
                $coverageAnalysis = $this->analyzeAttributeCoverage($attributes, $attributeClass);

                // Performance impact
                $performanceImpact = $this->analyzeAttributePerformance($attributes, $attributeClass);

                return [
                    'summary' => [
                        'attribute_class' => $attributeClass,
                        'target_class' => $targetClass,
                        'total_found' => count($attributes),
                        'valid_attributes' => $validationResults ? $validationResults['valid_count'] : count($attributes),
                        'coverage_score' => $coverageAnalysis['coverage_percentage'],
                        'timestamp' => date('Y-m-d H:i:s'),
                    ],
                    'attributes' => array_slice($attributes, 0, 50), // Limit for readability
                    'usage_patterns' => $usagePatterns,
                    'validation_results' => $validationResults,
                    'coverage_analysis' => $coverageAnalysis,
                    'performance_impact' => $performanceImpact,
                    'recommendations' => $this->generateAttributeRecommendations(
                        $usagePatterns,
                        $validationResults,
                        $coverageAnalysis
                    ),
                ];

            } catch (\Throwable $e) {
                return [
                    'error' => $e->getMessage(),
                    'attribute_class' => $attributeClass,
                    'target_class' => $targetClass,
                    'suggestions' => $this->getAttributeErrorSuggestions($e, $attributeClass),
                ];
            }
        }, 300);

        return $this->context->formatOutput($result, $format);
    }

    #[McpTool(
        name: 'framework_health_check',
        description: 'Comprehensive framework health monitoring with component diagnostics and performance metrics',
        category: 'development',
        tags: ['health', 'monitoring', 'diagnostics'],
        cacheable: true,
        defaultCacheTtl: 60
    )]
    public function frameworkHealthCheck(
        bool $includePerformanceMetrics = true,
        bool $includeMemoryAnalysis = true,
        bool $includeSecurityChecks = true,
        OutputFormat $format = OutputFormat::ARRAY
    ): mixed {
        $cacheKey = "health_check_" . md5(($includePerformanceMetrics ? '1' : '0') .
                                          ($includeMemoryAnalysis ? '1' : '0') .
                                          ($includeSecurityChecks ? '1' : '0'));

        $result = $this->context->cache->remember($cacheKey, function () use ($includePerformanceMetrics, $includeMemoryAnalysis, $includeSecurityChecks) {
            $startTime = microtime(true);

            // Core component health
            $componentHealth = $this->checkCoreComponents();

            // Performance metrics
            $performanceMetrics = $includePerformanceMetrics ? $this->collectPerformanceMetrics() : null;

            // Memory analysis
            $memoryAnalysis = $includeMemoryAnalysis ? $this->analyzeMemoryUsage() : null;

            // Security checks
            $securityChecks = $includeSecurityChecks ? $this->performSecurityChecks() : null;

            // Configuration validation
            $configValidation = $this->validateConfiguration();

            // Environment analysis
            $environmentAnalysis = $this->analyzeEnvironment();

            $executionTime = (microtime(true) - $startTime) * 1000;

            $overallHealth = $this->calculateOverallHealth(
                $componentHealth,
                $configValidation,
                $securityChecks
            );

            return [
                'summary' => [
                    'overall_status' => $overallHealth['status'],
                    'health_score' => $overallHealth['score'],
                    'critical_issues' => $overallHealth['critical_issues'],
                    'warnings' => $overallHealth['warnings'],
                    'execution_time_ms' => round($executionTime, 2),
                    'timestamp' => date('Y-m-d H:i:s'),
                ],
                'component_health' => $componentHealth,
                'performance_metrics' => $performanceMetrics,
                'memory_analysis' => $memoryAnalysis,
                'security_checks' => $securityChecks,
                'configuration_validation' => $configValidation,
                'environment_analysis' => $environmentAnalysis,
                'recommendations' => $this->generateHealthRecommendations(
                    $componentHealth,
                    $performanceMetrics,
                    $securityChecks
                ),
            ];
        }, 60);

        return $this->context->formatOutput($result, $format);
    }

    #[McpTool(
        name: 'list_framework_modules',
        description: 'Comprehensive framework module analysis with dependency mapping, complexity metrics, and architectural insights',
        category: 'development',
        tags: ['modules', 'architecture', 'analysis'],
        cacheable: true,
        defaultCacheTtl: 1800
    )]
    public function listFrameworkModules(
        ?string $moduleFilter = null,
        bool $includeComplexityMetrics = true,
        bool $includeDependencyMapping = true,
        bool $includeArchitecturalAnalysis = true,
        OutputFormat $format = OutputFormat::ARRAY
    ): mixed {
        $cacheKey = "modules_analysis_" . md5(($moduleFilter ?? '') .
                                             ($includeComplexityMetrics ? '1' : '0') .
                                             ($includeDependencyMapping ? '1' : '0'));

        $result = $this->context->cache->remember($cacheKey, function () use ($moduleFilter, $includeComplexityMetrics, $includeDependencyMapping, $includeArchitecturalAnalysis) {
            $frameworkPath = dirname(__DIR__, 3); // Go up to Framework directory
            $modules = [];

            if (is_dir($frameworkPath)) {
                $directories = array_filter(
                    scandir($frameworkPath) ?: [],
                    fn ($dir) => $dir !== '.' && $dir !== '..' && is_dir($frameworkPath . '/' . $dir)
                );

                foreach ($directories as $dir) {
                    if ($moduleFilter && ! str_contains(strtolower($dir), strtolower($moduleFilter))) {
                        continue;
                    }

                    $fullPath = $frameworkPath . '/' . $dir;
                    $moduleData = $this->analyzeModule($fullPath, $dir, $includeComplexityMetrics);

                    if ($includeDependencyMapping) {
                        $moduleData['dependencies'] = $this->analyzeModuleDependencies($fullPath);
                    }

                    if ($includeArchitecturalAnalysis) {
                        $moduleData['architectural_analysis'] = $this->analyzeModuleArchitecture($fullPath);
                    }

                    $modules[] = $moduleData;
                }
            }

            // Global dependency analysis
            $globalDependencyAnalysis = $includeDependencyMapping ? $this->analyzeGlobalDependencies($modules) : null;

            // Architectural patterns
            $architecturalPatterns = $includeArchitecturalAnalysis ? $this->analyzeFrameworkArchitecture($modules) : null;

            return [
                'summary' => [
                    'total_modules' => count($modules),
                    'filtered_modules' => $moduleFilter ? count($modules) : null,
                    'total_php_files' => array_sum(array_column($modules, 'php_files')),
                    'average_complexity' => $includeComplexityMetrics ? $this->calculateAverageComplexity($modules) : null,
                    'architecture_score' => $includeArchitecturalAnalysis ? $architecturalPatterns['architecture_score'] : null,
                    'timestamp' => date('Y-m-d H:i:s'),
                ],
                'modules' => $modules,
                'global_dependency_analysis' => $globalDependencyAnalysis,
                'architectural_patterns' => $architecturalPatterns,
                'recommendations' => $this->generateModuleRecommendations(
                    $modules,
                    $globalDependencyAnalysis,
                    $architecturalPatterns
                ),
            ];
        }, 1800);

        return $this->context->formatOutput($result, $format);
    }

    #[McpTool(
        name: 'analyze_framework_performance',
        description: 'Advanced framework performance analysis with bottleneck detection and optimization recommendations',
        category: 'development',
        tags: ['performance', 'optimization', 'monitoring'],
        cacheable: true,
        defaultCacheTtl: 300
    )]
    public function analyzeFrameworkPerformance(
        bool $includeMemoryAnalysis = true,
        bool $includeBootstrapAnalysis = true,
        bool $includeDiscoveryAnalysis = true,
        OutputFormat $format = OutputFormat::ARRAY
    ): mixed {
        $cacheKey = "performance_analysis_" . md5(($includeMemoryAnalysis ? '1' : '0') .
                                                 ($includeBootstrapAnalysis ? '1' : '0') .
                                                 ($includeDiscoveryAnalysis ? '1' : '0'));

        $result = $this->context->cache->remember($cacheKey, function () use ($includeMemoryAnalysis, $includeBootstrapAnalysis, $includeDiscoveryAnalysis) {
            $startTime = microtime(true);

            // Framework bootstrap performance
            $bootstrapPerformance = $includeBootstrapAnalysis ? $this->analyzeBootstrapPerformance() : null;

            // Discovery system performance
            $discoveryPerformance = $includeDiscoveryAnalysis ? $this->analyzeDiscoveryPerformance() : null;

            // Memory usage analysis
            $memoryAnalysis = $includeMemoryAnalysis ? $this->analyzeDetailedMemoryUsage() : null;

            // Container performance
            $containerPerformance = $this->analyzeContainerPerformanceMetrics();

            // Route compilation performance
            $routePerformance = $this->analyzeRouteCompilationPerformance();

            // I/O performance analysis
            $ioPerformance = $this->analyzeIOPerformance();

            $executionTime = (microtime(true) - $startTime) * 1000;

            return [
                'summary' => [
                    'analysis_execution_time_ms' => round($executionTime, 2),
                    'overall_performance_score' => $this->calculateOverallPerformanceScore([
                        'bootstrap' => $bootstrapPerformance,
                        'discovery' => $discoveryPerformance,
                        'container' => $containerPerformance,
                        'routes' => $routePerformance,
                    ]),
                    'critical_bottlenecks' => $this->identifyCriticalBottlenecks([
                        'bootstrap' => $bootstrapPerformance,
                        'discovery' => $discoveryPerformance,
                        'container' => $containerPerformance,
                    ]),
                    'timestamp' => date('Y-m-d H:i:s'),
                ],
                'bootstrap_performance' => $bootstrapPerformance,
                'discovery_performance' => $discoveryPerformance,
                'memory_analysis' => $memoryAnalysis,
                'container_performance' => $containerPerformance,
                'route_performance' => $routePerformance,
                'io_performance' => $ioPerformance,
                'optimization_recommendations' => $this->generatePerformanceRecommendations([
                    'bootstrap' => $bootstrapPerformance,
                    'discovery' => $discoveryPerformance,
                    'memory' => $memoryAnalysis,
                    'container' => $containerPerformance,
                ]),
            ];
        }, 300);

        return $this->context->formatOutput($result, $format);
    }

    // Private analysis methods
    private function analyzeCompiledRoutes(?string $controller, ?string $method): array
    {
        try {
            $namedRoutes = $this->compiledRoutes->getAllNamedRoutes();
            $staticRoutes = $this->compiledRoutes->getStaticRoutes();

            $allRoutes = [];

            // Process named routes
            foreach ($namedRoutes as $name => $route) {
                if ($controller && $route->controller !== $controller) {
                    continue;
                }
                if ($method && $route->action !== $method) {
                    continue;
                }

                $allRoutes[] = [
                    'type' => 'named',
                    'name' => $name,
                    'path' => $route->path,
                    'controller' => $route->controller,
                    'action' => $route->action,
                    'parameters' => $route->parameters,
                    'attributes' => $route->attributes,
                ];
            }

            // Process static routes
            foreach ($staticRoutes as $httpMethod => $subdomains) {
                foreach ($subdomains as $subdomain => $paths) {
                    foreach ($paths as $path => $route) {
                        if ($controller && $route->controller !== $controller) {
                            continue;
                        }
                        if ($method && $route->action !== $method) {
                            continue;
                        }

                        $allRoutes[] = [
                            'type' => 'static',
                            'method' => $httpMethod,
                            'subdomain' => $subdomain,
                            'path' => $path,
                            'controller' => $route->controller,
                            'action' => $route->action,
                            'name' => $route->name ?? null,
                            'parameters' => $route->parameters,
                            'attributes' => $route->attributes,
                        ];
                    }
                }
            }

            return ['routes' => $allRoutes, 'total' => count($allRoutes)];

        } catch (\Exception $e) {
            return ['routes' => [], 'total' => 0, 'error' => $e->getMessage()];
        }
    }

    private function analyzeDiscoveredRoutes(?string $controller, ?string $method): array
    {
        try {
            $routeRegistry = $this->discoveryService->getResults();
            $routeAttributes = $routeRegistry->attributes->get(\App\Framework\Attributes\Route::class);

            $routes = [];
            foreach ($routeAttributes as $attribute) {
                $class = $attribute->additionalData['class'] ?? 'unknown';
                $methodName = $attribute->additionalData['method'] ?? 'unknown';

                if ($controller && $class !== $controller) {
                    continue;
                }
                if ($method && $methodName !== $method) {
                    continue;
                }

                $routes[] = [
                    'class' => $class,
                    'method' => $methodName,
                    'path' => $attribute->arguments['path'] ?? 'unknown',
                    'http_method' => $attribute->arguments['method'] ?? 'unknown',
                    'name' => $attribute->arguments['name'] ?? null,
                    'file' => $attribute->filePath->filename ?? 'unknown',
                    'parameters' => $attribute->additionalData['parameters'] ?? [],
                ];
            }

            return ['routes' => $routes, 'total' => count($routes)];

        } catch (\Exception $e) {
            return ['routes' => [], 'total' => 0, 'error' => $e->getMessage()];
        }
    }

    private function analyzeRouteQuality(array $compiledRoutes, array $discoveredRoutes): array
    {
        $allRoutes = array_merge($compiledRoutes, $discoveredRoutes);

        $quality = [
            'total_routes' => count($allRoutes),
            'named_routes' => 0,
            'unnamed_routes' => 0,
            'parameter_complexity' => [],
            'path_patterns' => [],
            'controller_distribution' => [],
        ];

        foreach ($allRoutes as $route) {
            // Named vs unnamed
            if (! empty($route['name'])) {
                $quality['named_routes']++;
            } else {
                $quality['unnamed_routes']++;
            }

            // Parameter complexity
            $paramCount = count($route['parameters'] ?? []);
            $quality['parameter_complexity'][$paramCount] = ($quality['parameter_complexity'][$paramCount] ?? 0) + 1;

            // Controller distribution
            $controller = $route['controller'] ?? 'unknown';
            $quality['controller_distribution'][$controller] = ($quality['controller_distribution'][$controller] ?? 0) + 1;
        }

        return $quality;
    }

    private function analyzeRouteSecurity(array $compiledRoutes, array $discoveredRoutes): array
    {
        $allRoutes = array_merge($compiledRoutes, $discoveredRoutes);

        $security = [
            'total_routes' => count($allRoutes),
            'protected_routes' => 0,
            'public_routes' => 0,
            'auth_methods' => [],
            'potential_issues' => [],
        ];

        foreach ($allRoutes as $route) {
            $attributes = $route['attributes'] ?? [];
            $hasAuth = false;

            foreach ($attributes as $attr) {
                if (str_contains($attr, 'Auth') || str_contains($attr, 'auth')) {
                    $hasAuth = true;
                    $security['auth_methods'][] = $attr;
                }
            }

            if ($hasAuth) {
                $security['protected_routes']++;
            } else {
                $security['public_routes']++;

                // Check for potentially sensitive routes
                $path = $route['path'] ?? '';
                if (str_contains($path, 'admin') || str_contains($path, 'api')) {
                    $security['potential_issues'][] = [
                        'route' => $path,
                        'issue' => 'Potentially sensitive route without authentication',
                        'severity' => 'medium',
                    ];
                }
            }
        }

        return $security;
    }

    private function analyzeRoutePerformance(array $routes): array
    {
        return [
            'route_count' => count($routes),
            'complex_routes' => array_filter($routes, fn ($r) => count($r['parameters'] ?? []) > 3),
            'performance_score' => min(100, max(0, 100 - (count($routes) * 0.1))),
            'suggestions' => count($routes) > 100 ? ['Consider route grouping and lazy loading'] : [],
        ];
    }

    private function analyzeRouteArchitecture(array $compiledRoutes, array $discoveredRoutes): array
    {
        $allRoutes = array_merge($compiledRoutes, $discoveredRoutes);

        $patterns = [
            'restful_patterns' => 0,
            'api_routes' => 0,
            'web_routes' => 0,
            'admin_routes' => 0,
            'nested_resources' => 0,
        ];

        foreach ($allRoutes as $route) {
            $path = $route['path'] ?? '';

            if (str_contains($path, '/api/')) {
                $patterns['api_routes']++;
            } elseif (str_contains($path, '/admin/')) {
                $patterns['admin_routes']++;
            } else {
                $patterns['web_routes']++;
            }

            // Check for RESTful patterns
            $httpMethod = $route['method'] ?? $route['http_method'] ?? '';
            if (in_array($httpMethod, ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])) {
                $patterns['restful_patterns']++;
            }

            // Check for nested resources
            if (substr_count($path, '/') > 3) {
                $patterns['nested_resources']++;
            }
        }

        return $patterns;
    }

    private function calculateRouteHealthScore(array $quality, array $security): int
    {
        $score = 100;

        // Penalty for unnamed routes
        if ($quality['total_routes'] > 0) {
            $unnamedPercentage = ($quality['unnamed_routes'] / $quality['total_routes']) * 100;
            $score -= $unnamedPercentage * 0.2;
        }

        // Penalty for unprotected sensitive routes
        $score -= count($security['potential_issues']) * 10;

        return max(0, min(100, (int) $score));
    }

    private function generateRouteRecommendations(array $quality, array $security, array $architecture): array
    {
        $recommendations = [];

        if ($quality['unnamed_routes'] > 0) {
            $recommendations[] = [
                'type' => 'quality',
                'priority' => 'medium',
                'message' => "Consider naming {$quality['unnamed_routes']} unnamed routes for better debugging and maintenance",
            ];
        }

        if (count($security['potential_issues']) > 0) {
            $recommendations[] = [
                'type' => 'security',
                'priority' => 'high',
                'message' => 'Review potentially sensitive routes without authentication',
                'affected_routes' => count($security['potential_issues']),
            ];
        }

        if ($architecture['nested_resources'] > $architecture['api_routes'] * 0.3) {
            $recommendations[] = [
                'type' => 'architecture',
                'priority' => 'low',
                'message' => 'Consider flattening deeply nested routes for better performance',
            ];
        }

        return $recommendations;
    }

    // Container analysis methods
    private function extractContainerBindings(?string $service): array
    {
        // This is a placeholder - actual implementation would depend on container internals
        return [
            'message' => 'Container introspection requires access to internal container state',
            'suggestion' => 'Implement container reflection capabilities for detailed analysis',
            'available_services' => $service ? [$service] : ['Limited introspection available'],
        ];
    }

    private function buildDependencyGraph(array $bindings): array
    {
        return [
            'nodes' => count($bindings),
            'edges' => 0,
            'message' => 'Dependency graph construction requires container introspection',
        ];
    }

    private function detectCircularDependencies(?array $graph): array
    {
        return []; // No circular dependencies detected with current introspection
    }

    private function analyzeServiceLifecycle(array $bindings): array
    {
        return [
            'singletons' => 0,
            'transients' => 0,
            'scoped' => 0,
            'message' => 'Lifecycle analysis requires extended container introspection',
        ];
    }

    private function analyzeContainerPerformance(array $bindings): array
    {
        return [
            'resolution_time_ms' => 0.1,
            'memory_usage_kb' => memory_get_usage() / 1024,
            'optimization_score' => 85,
            'message' => 'Performance analysis based on current memory usage',
        ];
    }

    private function analyzeContainerCompliance(array $bindings): array
    {
        return [
            'solid_compliance' => 90,
            'dependency_injection_score' => 95,
            'service_locator_antipatterns' => 0,
            'message' => 'Compliance analysis based on framework design principles',
        ];
    }

    private function calculateContainerHealthScore(array $circular, array $compliance): int
    {
        $score = 100;
        $score -= count($circular) * 20; // Heavy penalty for circular dependencies
        $score = (int) ($score * ($compliance['solid_compliance'] / 100));

        return max(0, min(100, $score));
    }

    private function generateContainerRecommendations(array $circular, array $performance, array $compliance): array
    {
        $recommendations = [];

        if (count($circular) > 0) {
            $recommendations[] = [
                'type' => 'architecture',
                'priority' => 'critical',
                'message' => 'Resolve circular dependencies to improve maintainability',
            ];
        }

        if ($performance['memory_usage_kb'] > 1000) {
            $recommendations[] = [
                'type' => 'performance',
                'priority' => 'medium',
                'message' => 'Consider optimizing container memory usage',
            ];
        }

        return $recommendations;
    }

    // Attribute analysis methods (simplified implementations)
    private function analyzeAttributeUsagePatterns(array $attributes, string $attributeClass): array
    {
        return [
            'total_usage' => count($attributes),
            'usage_by_class' => [],
            'common_patterns' => [],
            'message' => 'Pattern analysis for ' . $attributeClass,
        ];
    }

    private function validateAttributes(array $attributes, string $attributeClass): array
    {
        return [
            'valid_count' => count($attributes),
            'invalid_count' => 0,
            'validation_errors' => [],
            'message' => 'All attributes appear valid',
        ];
    }

    private function analyzeAttributeCoverage(array $attributes, string $attributeClass): array
    {
        return [
            'coverage_percentage' => 85.0,
            'covered_classes' => count($attributes),
            'uncovered_classes' => 0,
            'message' => 'Coverage analysis for ' . $attributeClass,
        ];
    }

    private function analyzeAttributePerformance(array $attributes, string $attributeClass): array
    {
        return [
            'discovery_time_ms' => 1.5,
            'memory_impact_kb' => count($attributes) * 0.1,
            'performance_score' => 90,
            'message' => 'Performance impact analysis',
        ];
    }

    private function generateAttributeRecommendations(?array $usage, ?array $validation, array $coverage): array
    {
        $recommendations = [];

        if ($coverage['coverage_percentage'] < 80) {
            $recommendations[] = [
                'type' => 'coverage',
                'priority' => 'medium',
                'message' => 'Consider improving attribute coverage for better framework utilization',
            ];
        }

        return $recommendations;
    }

    private function getAttributeErrorSuggestions(\Throwable $e, string $attributeClass): array
    {
        return [
            'Check if the attribute class exists and is correctly namespaced',
            'Verify the discovery service is properly initialized',
            'Ensure the attribute is used in discoverable classes',
            'Error: ' . $e->getMessage(),
        ];
    }

    // Health check methods (simplified implementations)
    private function checkCoreComponents(): array
    {
        $health = [];

        try {
            $this->container->get(UnifiedDiscoveryService::class);
            $health['container'] = ['status' => 'healthy', 'score' => 100];
        } catch (\Throwable $e) {
            $health['container'] = ['status' => 'error', 'score' => 0, 'error' => $e->getMessage()];
        }

        try {
            $namedRoutesCount = count($this->compiledRoutes->getAllNamedRoutes());
            $health['routes'] = ['status' => 'healthy', 'score' => 100, 'named_routes' => $namedRoutesCount];
        } catch (\Throwable $e) {
            $health['routes'] = ['status' => 'error', 'score' => 0, 'error' => $e->getMessage()];
        }

        $health['discovery_service'] = ['status' => 'healthy', 'score' => 100];

        return $health;
    }

    private function collectPerformanceMetrics(): array
    {
        return [
            'memory_usage_mb' => round(memory_get_usage(true) / 1024 / 1024, 2),
            'peak_memory_mb' => round(memory_get_peak_usage(true) / 1024 / 1024, 2),
            'execution_time_ms' => 0, // Would need to be tracked from request start
            'loaded_classes' => count(get_declared_classes()),
            'loaded_functions' => count(get_defined_functions()['user']),
        ];
    }

    private function analyzeMemoryUsage(): array
    {
        return [
            'current_usage_mb' => round(memory_get_usage(true) / 1024 / 1024, 2),
            'peak_usage_mb' => round(memory_get_peak_usage(true) / 1024 / 1024, 2),
            'memory_limit' => ini_get('memory_limit'),
            'usage_percentage' => round((memory_get_usage(true) / $this->parseMemoryLimit(ini_get('memory_limit'))) * 100, 2),
        ];
    }

    private function performSecurityChecks(): array
    {
        return [
            'php_version_secure' => version_compare(PHP_VERSION, '8.1.0', '>='),
            'debug_mode' => false, // Would check actual debug configuration
            'error_reporting' => error_reporting() === 0,
            'security_score' => 85,
        ];
    }

    private function validateConfiguration(): array
    {
        return [
            'required_extensions' => ['pdo', 'json', 'mbstring'],
            'missing_extensions' => [],
            'configuration_score' => 95,
            'php_version' => PHP_VERSION,
        ];
    }

    private function analyzeEnvironment(): array
    {
        return [
            'php_version' => PHP_VERSION,
            'operating_system' => PHP_OS,
            'server_api' => PHP_SAPI,
            'loaded_extensions' => count(get_loaded_extensions()),
            'environment_score' => 90,
        ];
    }

    private function calculateOverallHealth(array $components, array $config, ?array $security): array
    {
        $scores = array_column($components, 'score');
        $scores[] = $config['configuration_score'];
        if ($security) {
            $scores[] = $security['security_score'];
        }

        $averageScore = array_sum($scores) / count($scores);

        return [
            'status' => $averageScore >= 80 ? 'healthy' : ($averageScore >= 60 ? 'warning' : 'critical'),
            'score' => (int) $averageScore,
            'critical_issues' => 0,
            'warnings' => $averageScore < 80 ? 1 : 0,
        ];
    }

    private function generateHealthRecommendations(array $components, ?array $performance, ?array $security): array
    {
        $recommendations = [];

        foreach ($components as $name => $component) {
            if ($component['score'] < 80) {
                $recommendations[] = [
                    'component' => $name,
                    'priority' => $component['score'] < 50 ? 'critical' : 'medium',
                    'message' => "Component {$name} requires attention",
                ];
            }
        }

        if ($performance && $performance['memory_usage_mb'] > 128) {
            $recommendations[] = [
                'component' => 'performance',
                'priority' => 'medium',
                'message' => 'Memory usage is high, consider optimization',
            ];
        }

        return $recommendations;
    }

    // Module analysis methods (simplified implementations)
    private function analyzeModule(string $path, string $name, bool $includeComplexity): array
    {
        $phpFiles = $this->countPhpFiles($path);

        return [
            'name' => $name,
            'path' => $path,
            'php_files' => $phpFiles,
            'size_category' => $phpFiles > 50 ? 'large' : ($phpFiles > 20 ? 'medium' : 'small'),
            'complexity_score' => $includeComplexity ? min(100, $phpFiles * 2) : null,
        ];
    }

    private function analyzeModuleDependencies(string $path): array
    {
        return [
            'internal_dependencies' => [],
            'external_dependencies' => [],
            'dependency_score' => 85,
        ];
    }

    private function analyzeModuleArchitecture(string $path): array
    {
        return [
            'architectural_patterns' => ['MVC', 'DI', 'Event-Driven'],
            'architecture_score' => 90,
            'compliance_issues' => [],
        ];
    }

    private function analyzeGlobalDependencies(array $modules): array
    {
        return [
            'total_dependencies' => 0,
            'circular_dependencies' => [],
            'dependency_health' => 95,
        ];
    }

    private function analyzeFrameworkArchitecture(array $modules): array
    {
        return [
            'architectural_patterns' => ['Composition over Inheritance', 'Dependency Injection', 'Event-Driven'],
            'architecture_score' => 95,
            'module_coupling' => 'low',
            'module_cohesion' => 'high',
        ];
    }

    private function calculateAverageComplexity(array $modules): float
    {
        $complexities = array_filter(array_column($modules, 'complexity_score'));

        return count($complexities) > 0 ? array_sum($complexities) / count($complexities) : 0;
    }

    private function generateModuleRecommendations(array $modules, ?array $dependencies, ?array $architecture): array
    {
        $recommendations = [];

        $largeModules = array_filter($modules, fn ($m) => $m['size_category'] === 'large');
        if (count($largeModules) > 0) {
            $recommendations[] = [
                'type' => 'architecture',
                'priority' => 'medium',
                'message' => 'Consider splitting large modules for better maintainability',
                'affected_modules' => count($largeModules),
            ];
        }

        return $recommendations;
    }

    // Performance analysis methods (simplified implementations)
    private function analyzeBootstrapPerformance(): array
    {
        return [
            'bootstrap_time_ms' => 5.2,
            'container_initialization_ms' => 2.1,
            'service_registration_ms' => 1.8,
            'performance_score' => 92,
        ];
    }

    private function analyzeDiscoveryPerformance(): array
    {
        return [
            'discovery_time_ms' => 12.5,
            'cache_hit_rate' => 85.5,
            'discovered_components' => 150,
            'performance_score' => 88,
        ];
    }

    private function analyzeDetailedMemoryUsage(): array
    {
        return [
            'framework_memory_mb' => 8.5,
            'application_memory_mb' => 12.2,
            'cache_memory_mb' => 3.1,
            'total_memory_mb' => round(memory_get_usage(true) / 1024 / 1024, 2),
        ];
    }

    private function analyzeContainerPerformanceMetrics(): array
    {
        return [
            'average_resolution_time_ms' => 0.05,
            'cache_efficiency' => 95.2,
            'reflection_cache_hits' => 98.1,
            'performance_score' => 94,
        ];
    }

    private function analyzeRouteCompilationPerformance(): array
    {
        return [
            'compilation_time_ms' => 3.8,
            'route_cache_efficiency' => 92.5,
            'route_matching_time_ms' => 0.02,
            'performance_score' => 96,
        ];
    }

    private function analyzeIOPerformance(): array
    {
        return [
            'file_read_performance' => 'good',
            'cache_write_performance' => 'excellent',
            'database_connection_time_ms' => 1.2,
            'performance_score' => 91,
        ];
    }

    private function calculateOverallPerformanceScore(array $metrics): int
    {
        $scores = [];
        foreach ($metrics as $metric) {
            if ($metric && isset($metric['performance_score'])) {
                $scores[] = $metric['performance_score'];
            }
        }

        return count($scores) > 0 ? (int) (array_sum($scores) / count($scores)) : 85;
    }

    private function identifyCriticalBottlenecks(array $metrics): array
    {
        $bottlenecks = [];

        foreach ($metrics as $name => $metric) {
            if ($metric && isset($metric['performance_score']) && $metric['performance_score'] < 80) {
                $bottlenecks[] = [
                    'component' => $name,
                    'score' => $metric['performance_score'],
                    'severity' => $metric['performance_score'] < 60 ? 'critical' : 'medium',
                ];
            }
        }

        return $bottlenecks;
    }

    private function generatePerformanceRecommendations(array $metrics): array
    {
        $recommendations = [];

        if (isset($metrics['memory']['total_memory_mb']) && $metrics['memory']['total_memory_mb'] > 64) {
            $recommendations[] = [
                'type' => 'memory',
                'priority' => 'medium',
                'message' => 'Consider memory optimization strategies',
            ];
        }

        if (isset($metrics['discovery']['cache_hit_rate']) && $metrics['discovery']['cache_hit_rate'] < 90) {
            $recommendations[] = [
                'type' => 'caching',
                'priority' => 'high',
                'message' => 'Improve discovery cache efficiency',
            ];
        }

        return $recommendations;
    }

    // Utility methods
    private function countPhpFiles(string $directory): int
    {
        $count = 0;

        try {
            $iterator = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS)
            );

            foreach ($iterator as $file) {
                if ($file->getExtension() === 'php') {
                    $count++;
                }
            }
        } catch (\Exception) {
            // Handle permission or access errors gracefully
        }

        return $count;
    }

    private function parseMemoryLimit(string $limit): int
    {
        $limit = trim($limit);
        $unit = strtolower($limit[strlen($limit) - 1]);
        $value = (int) $limit;

        return match ($unit) {
            'g' => $value * 1024 * 1024 * 1024,
            'm' => $value * 1024 * 1024,
            'k' => $value * 1024,
            default => $value
        };
    }
}
