<?php

declare(strict_types=1);

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

use App\Framework\Core\Environment;
use App\Framework\DI\DefaultContainer;
use App\Framework\Discovery\UnifiedDiscoveryService;
use App\Framework\Filesystem\FileScanner;
use App\Framework\Mcp\Tools\SecurityAuditTools;
use App\Framework\Mcp\Tools\SecurityConfigurationTools;
use App\Framework\Mcp\Tools\SecurityMonitoringTools;
use App\Framework\Reflection\CachedReflectionProvider;
use App\Framework\Router\CompiledRoutes;

echo "=== Testing Security Audit MCP Tools ===\n\n";

// Setup basic dependencies
$container = new DefaultContainer();
$reflectionProvider = new CachedReflectionProvider();
$fileScanner = new FileScanner();

// Mock UnifiedDiscoveryService - create a stub since it's a concrete class
$discoveryService = new class () {
    public function discover(string $attributeClass): array
    {
        return [];
    }

    public function getCache(): array
    {
        return [];
    }

    public function clearCache(): void
    {
    }

    public function warmUp(): void
    {
    }
};

// Mock CompiledRoutes - create a stub since it's a concrete class
$compiledRoutes = new class () {
    public function getStaticRoutes(): array
    {
        return [
            [
                'path' => '/admin/dashboard',
                'method' => 'GET',
                'file' => 'src/Application/Admin/Dashboard.php',
                'line' => 25,
                'auth' => true,
            ],
            [
                'path' => '/api/sensitive-data',
                'method' => 'GET',
                'file' => 'src/Application/Api/SensitiveController.php',
                'line' => 15,
                // No auth protection - vulnerability!
            ],
            [
                'path' => '/api/users',
                'method' => 'POST',
                'file' => 'src/Application/Api/UserController.php',
                'line' => 30,
                'auth' => true,
                // No CSRF protection - vulnerability!
            ],
        ];
    }

    public function getDynamicRoutes(): array
    {
        return [];
    }

    public function findStaticRoute(string $method, string $path): ?array
    {
        return null;
    }

    public function findDynamicRoute(string $method, string $path): ?array
    {
        return null;
    }
};

// Mock Environment - create a stub since it's a concrete class
$environment = new class () {
    public function get(string $key, mixed $default = null): mixed
    {
        return match($key) {
            'APP_ENV' => 'development',
            'APP_DEBUG' => true,
            default => $default
        };
    }

    public function getInt(string $key, int $default = 0): int
    {
        return $default;
    }

    public function getBool(string $key, bool $default = false): bool
    {
        return $default;
    }

    public function require(string $key): mixed
    {
        return 'required_value';
    }

    public function has(string $key): bool
    {
        return true;
    }

    public function all(): array
    {
        return [];
    }
};

// Mock Logger
$logger = new class () implements \Psr\Log\LoggerInterface {
    use \Psr\Log\LoggerTrait;

    public function log($level, string|\Stringable $message, array $context = []): void
    {
        // Mock implementation
    }
};

echo "1. Testing SecurityAuditTools:\n\n";

try {
    $securityAuditTools = new SecurityAuditTools(
        container: $container,
        discoveryService: $discoveryService,
        reflectionProvider: $reflectionProvider,
        fileScanner: $fileScanner,
        compiledRoutes: $compiledRoutes
    );

    echo "   🔍 Running security vulnerability scan:\n";
    $vulnerabilityResults = $securityAuditTools->securityVulnerabilityScan(
        path: 'src/',
        severity: 'medium',
        includeOwasp: true
    );

    echo "      ✅ Vulnerability scan completed\n";
    echo "      📊 Total vulnerabilities: {$vulnerabilityResults['scan_summary']['total_vulnerabilities']}\n";
    echo "      🔴 Critical: {$vulnerabilityResults['scan_summary']['critical']}\n";
    echo "      🟠 High: {$vulnerabilityResults['scan_summary']['high']}\n";
    echo "      🟡 Medium: {$vulnerabilityResults['scan_summary']['medium']}\n";
    echo "      🔵 Low: {$vulnerabilityResults['scan_summary']['low']}\n\n";

    echo "   🔐 Analyzing authentication patterns:\n";
    $authResults = $securityAuditTools->analyzeAuthPatterns(
        includeRoutes: true,
        checkMiddleware: true
    );

    echo "      ✅ Authentication analysis completed\n";
    if (isset($authResults['route_authentication'])) {
        echo "      🛡️ Protected routes: {$authResults['authentication_summary']['protected_routes']}\n";
        echo "      ⚠️ Unprotected routes: {$authResults['authentication_summary']['unprotected_routes']}\n";
    }
    echo "\n";

    echo "   📋 Running OWASP compliance scan:\n";
    $owaspResults = $securityAuditTools->scanOwaspCompliance(
        categories: ['A01_broken_access_control', 'A03_injection'],
        detailedReport: true
    );

    echo "      ✅ OWASP compliance scan completed\n";
    echo "      📊 Overall score: {$owaspResults['overall_score']}%\n";
    echo "      🏆 Compliance level: {$owaspResults['compliance_level']}\n";
    echo "      🚨 Critical findings: " . count($owaspResults['critical_findings']) . "\n\n";

    echo "   📈 Generating security metrics report:\n";
    $metricsResults = $securityAuditTools->securityMetricsReport(
        includeTrends: false,
        reportFormat: 'summary'
    );

    echo "      ✅ Security metrics report generated\n";
    echo "      🎯 Security score: {$metricsResults['security_overview']['security_score']}\n";
    echo "      📊 Total vulnerabilities: {$metricsResults['security_overview']['total_vulnerabilities']}\n\n";

    echo "   🎯 Running threat detection scan:\n";
    $threatResults = $securityAuditTools->threatDetectionScan(
        threatTypes: ['sql_injection', 'xss', 'csrf'],
        scanDepth: 'deep'
    );

    echo "      ✅ Threat detection scan completed\n";
    echo "      🔍 Threats analyzed: " . count($threatResults['detected_threats']) . " types\n";
    echo "      ⚠️ Risk level: {$threatResults['risk_assessment']['risk_level']}\n\n";

} catch (\Throwable $e) {
    echo "      ❌ Error testing SecurityAuditTools: {$e->getMessage()}\n\n";
}

echo "2. Testing SecurityConfigurationTools:\n\n";

try {
    $securityConfigTools = new SecurityConfigurationTools(
        container: $container,
        environment: $environment
    );

    echo "   🛡️ Analyzing security headers:\n";
    $headersResults = $securityConfigTools->analyzeSecurityHeaders(
        checkProduction: true,
        includeRecommendations: true
    );

    echo "      ✅ Security headers analysis completed\n";
    echo "      📊 Compliance score: {$headersResults['compliance_score']}%\n";
    echo "      🔧 Configured headers: {$headersResults['security_headers_summary']['configured_headers_count']}\n";
    echo "      ⚠️ Missing headers: {$headersResults['security_headers_summary']['missing_headers_count']}\n\n";

    echo "   🔥 WAF configuration audit:\n";
    $wafResults = $securityConfigTools->wafConfigurationAudit(
        includeRuleAnalysis: true,
        checkBypassAttempts: false
    );

    echo "      ✅ WAF configuration audit completed\n";
    echo "      🛡️ WAF enabled: " . ($wafResults['waf_summary']['waf_enabled'] ? 'YES' : 'NO') . "\n";
    if (! $wafResults['waf_summary']['waf_enabled']) {
        echo "      💡 Recommendation: {$wafResults['waf_summary']['recommendation']}\n";
    }
    echo "\n";

    echo "   🌍 Environment security check:\n";
    $envResults = $securityConfigTools->environmentSecurityCheck(
        checkSecrets: true,
        validatePermissions: true
    );

    echo "      ✅ Environment security check completed\n";
    echo "      🌍 Environment: {$envResults['environment_summary']['environment']}\n";
    echo "      🐛 Debug mode: " . ($envResults['environment_summary']['debug_mode'] ? 'ENABLED' : 'DISABLED') . "\n";
    echo "      🔒 Security appropriate: " . ($envResults['environment_summary']['security_appropriate'] ? 'YES' : 'NO') . "\n";
    echo "      ⚠️ Security issues: " . count($envResults['security_issues']) . "\n\n";

    echo "   🔐 SSL/TLS configuration audit:\n";
    $sslResults = $securityConfigTools->sslTlsConfigurationAudit(
        checkCertificates: true,
        validateProtocols: true
    );

    echo "      ✅ SSL/TLS configuration audit completed\n";
    echo "      🔒 Security score: {$sslResults['security_score']}\n\n";

    echo "   🛡️ Security middleware analysis:\n";
    $middlewareResults = $securityConfigTools->securityMiddlewareAnalysis(
        checkCoverage: true,
        validateOrder: true
    );

    echo "      ✅ Security middleware analysis completed\n";
    echo "      🔧 Security middleware count: {$middlewareResults['middleware_summary']['total_security_middleware']}\n";
    echo "      📊 Coverage percentage: {$middlewareResults['middleware_summary']['coverage_percentage']}%\n\n";

} catch (\Throwable $e) {
    echo "      ❌ Error testing SecurityConfigurationTools: {$e->getMessage()}\n\n";
}

echo "3. Testing SecurityMonitoringTools:\n\n";

try {
    $securityMonitoringTools = new SecurityMonitoringTools(
        container: $container,
        logger: $logger
    );

    echo "   📊 Security events analysis:\n";
    $eventsResults = $securityMonitoringTools->securityEventsAnalysis(
        timeWindow: '24h',
        severityFilter: 'medium',
        eventTypes: ['authentication_failure', 'sql_injection_attempt']
    );

    echo "      ✅ Security events analysis completed\n";
    echo "      📈 Total events: {$eventsResults['analysis_summary']['total_events']}\n";
    echo "      🕐 Time window: {$eventsResults['analysis_summary']['time_window']}\n";
    echo "      🎯 Severity filter: {$eventsResults['analysis_summary']['severity_filter']}\n\n";

    echo "   🎯 Threat intelligence report:\n";
    $threatIntelResults = $securityMonitoringTools->threatIntelligenceReport(
        reportPeriod: '7d',
        includeIoc: true,
        threatLevelThreshold: 'medium'
    );

    echo "      ✅ Threat intelligence report generated\n";
    echo "      📊 Threats analyzed: {$threatIntelResults['threat_intelligence_summary']['total_threats_analyzed']}\n";
    echo "      📋 Report period: {$threatIntelResults['threat_intelligence_summary']['report_period']}\n";
    echo "      🎯 Threat threshold: {$threatIntelResults['threat_intelligence_summary']['threat_level_threshold']}\n\n";

    echo "   ⚡ Real-time security status:\n";
    $statusResults = $securityMonitoringTools->realTimeSecurityStatus(
        includeMetrics: true,
        checkActiveSessions: true
    );

    echo "      ✅ Real-time security status retrieved\n";
    echo "      🛡️ Overall security level: {$statusResults['security_status_summary']['overall_security_level']}\n";
    echo "      🚨 Active threats: {$statusResults['security_status_summary']['active_threats']}\n";
    echo "      💚 System status: {$statusResults['security_status_summary']['system_status']}\n\n";

    echo "   🚨 Incident response analysis:\n";
    $incidentResults = $securityMonitoringTools->incidentResponseAnalysis(
        incidentId: null,
        incidentType: 'unauthorized_access',
        severityLevel: 'medium',
        timeRange: '24h'
    );

    echo "      ✅ Incident response analysis completed\n";
    echo "      📊 Total incidents: {$incidentResults['incident_analysis_summary']['total_incidents']}\n";
    echo "      🔒 Severity filter: {$incidentResults['incident_analysis_summary']['severity_filter']}\n\n";

    echo "   📋 Security compliance monitoring:\n";
    $complianceResults = $securityMonitoringTools->securityComplianceMonitoring(
        complianceFrameworks: ['owasp', 'gdpr'],
        monitoringPeriod: '30d',
        includeEvidence: true
    );

    echo "      ✅ Security compliance monitoring completed\n";
    echo "      📊 Frameworks monitored: " . count($complianceResults['compliance_monitoring_summary']['frameworks_monitored']) . "\n";
    echo "      🎯 Overall compliance score: {$complianceResults['overall_compliance_score']}%\n\n";

} catch (\Throwable $e) {
    echo "      ❌ Error testing SecurityMonitoringTools: {$e->getMessage()}\n\n";
}

echo "=== Security Audit MCP Tools Test Completed ===\n";
echo "\n🎯 Summary of Security Tools:\n";
echo "   1. ✅ SecurityAuditTools - Vulnerability scanning and OWASP compliance\n";
echo "   2. ✅ SecurityConfigurationTools - Security headers, WAF, SSL/TLS, environment\n";
echo "   3. ✅ SecurityMonitoringTools - Real-time monitoring and threat intelligence\n";
echo "\n💡 Key Security Features Implemented:\n";
echo "   • Comprehensive vulnerability scanning with OWASP classification\n";
echo "   • Authentication and authorization pattern analysis\n";
echo "   • Security configuration auditing (headers, WAF, SSL/TLS)\n";
echo "   • Real-time security monitoring and threat detection\n";
echo "   • Incident response analysis and compliance monitoring\n";
echo "   • Threat intelligence reporting with IoC analysis\n";
echo "\n🛡️ The Security Audit MCP Tools provide enterprise-grade security analysis!\n";
