<?php

declare(strict_types=1);

/**
 * N+1 Detection Machine Learning - Usage Example
 *
 * This example demonstrates how to use the N+1 Detection ML Engine
 * to analyze query execution patterns and detect N+1 query problems.
 */

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

use App\Framework\Database\NPlusOneDetection\MachineLearning\NPlusOneDetectionEngine;
use App\Framework\Database\NPlusOneDetection\MachineLearning\NPlusOneDetectionEngineInitializer;
use App\Framework\Database\NPlusOneDetection\QueryExecutionContext;
use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Config\Environment;
use App\Framework\DateTime\SystemClock;
use App\Framework\Logging\Handlers\ConsoleHandler;
use App\Framework\Logging\Logger;
use App\Framework\Logging\LogLevel;

echo "=== N+1 Detection Machine Learning - Usage Example ===\n\n";

// Setup
$environment = new Environment();
$clock = new SystemClock();
$logger = new Logger([new ConsoleHandler(LogLevel::INFO)]);

// Initialize N+1 Detection ML Engine
$initializer = new NPlusOneDetectionEngineInitializer($environment, $clock, $logger);
$engine = $initializer();

echo "✓ N+1 Detection ML Engine initialized\n";
echo "Configuration: " . json_encode($engine->getConfiguration(), JSON_PRETTY_PRINT) . "\n\n";

// Example 1: Clean Query Pattern (No N+1)
echo "=== Example 1: Clean Query Pattern (No N+1) ===\n";
$cleanContext = QueryExecutionContext::fromQueries([
    [
        'query' => 'SELECT * FROM users WHERE id = 1',
        'duration' => 5.0,
        'complexity' => 0.3,
        'joins' => 0,
    ],
    [
        'query' => 'SELECT * FROM posts WHERE user_id = 1',
        'duration' => 8.0,
        'complexity' => 0.4,
        'joins' => 0,
    ],
], executedInLoop: false);

$result1 = $engine->analyzeQueryContext($cleanContext);
echo "Analysis Result:\n";
echo "  - Success: " . ($result1['success'] ? 'Yes' : 'No') . "\n";
echo "  - Features Extracted: " . count($result1['features']) . "\n";
echo "  - Anomalies Detected: " . count($result1['anomalies']) . "\n";
echo "  - Overall Confidence: " . round($result1['overall_confidence'], 2) . "%\n";
echo "  - Analysis Time: " . round($result1['analysis_time_ms'], 2) . "ms\n";
echo "  - Has N+1 Pattern: " . ($cleanContext->hasNPlusOnePattern() ? 'Yes' : 'No') . "\n\n";

// Example 2: Suspicious N+1 Pattern
echo "=== Example 2: Suspicious N+1 Pattern ===\n";
$queries = [];
// Simulate N+1: 1 initial query + 10 repeated queries in loop
$queries[] = [
    'query' => 'SELECT * FROM users',
    'duration' => 10.0,
    'complexity' => 0.5,
    'joins' => 0,
];
for ($i = 1; $i <= 10; $i++) {
    $queries[] = [
        'query' => "SELECT * FROM posts WHERE user_id = {$i}",  // Will be normalized to same hash
        'duration' => 5.0 + ($i * 0.1),  // Slightly varying timing
        'complexity' => 0.3,
        'joins' => 0,
    ];
}

$suspiciousContext = QueryExecutionContext::fromQueries($queries, executedInLoop: true, loopDepth: 1);

$result2 = $engine->analyzeQueryContext($suspiciousContext);
echo "Analysis Result:\n";
echo "  - Success: " . ($result2['success'] ? 'Yes' : 'No') . "\n";
echo "  - Features Extracted: " . count($result2['features']) . "\n";
echo "  - Anomalies Detected: " . count($result2['anomalies']) . "\n";
echo "  - Overall Confidence: " . round($result2['overall_confidence'], 2) . "%\n";
echo "  - Analysis Time: " . round($result2['analysis_time_ms'], 2) . "ms\n";
echo "  - Has N+1 Pattern: " . ($suspiciousContext->hasNPlusOnePattern() ? '⚠️  Yes' : 'No') . "\n";
echo "  - Repetition Rate: " . round($suspiciousContext->getRepetitionRate(), 2) . "%\n";
echo "  - Unique Queries: " . count($suspiciousContext->uniqueQueryHashes) . " / " . $suspiciousContext->queryCount . "\n\n";

// Show detected anomalies
if (!empty($result2['anomalies'])) {
    echo "Detected Anomalies:\n";
    foreach ($result2['anomalies'] as $anomaly) {
        echo "  - Type: {$anomaly->type->value}\n";
        echo "    Confidence: " . round($anomaly->confidence->value, 2) . "%\n";
        echo "    Severity: {$anomaly->severity->value}\n";
        echo "    Description: {$anomaly->description}\n";
        if (!empty($anomaly->context)) {
            echo "    Context: " . json_encode($anomaly->context) . "\n";
        }
        echo "\n";
    }
}

// Show extracted features
echo "=== Extracted Features (Sample) ===\n";
if (!empty($result2['features'])) {
    $sampleFeatures = array_slice($result2['features'], 0, 3);
    foreach ($sampleFeatures as $feature) {
        echo "  - {$feature->name}: " . round($feature->value, 4) . " {$feature->unit}\n";
        echo "    Type: {$feature->type->value}\n";
        if (!empty($feature->metadata)) {
            echo "    Metadata: " . json_encode($feature->metadata) . "\n";
        }
        echo "\n";
    }
}

// Example 3: Disabled Engine
echo "=== Example 3: Disabled Engine ===\n";
$disabledEngine = new NPlusOneDetectionEngine(
    enabled: false,
    extractors: [],
    detectors: [],
    clock: $clock,
    analysisTimeout: Duration::fromSeconds(5),
    confidenceThreshold: \App\Framework\Core\ValueObjects\Percentage::from(60.0)
);

$result3 = $disabledEngine->analyzeQueryContext($suspiciousContext);
echo "Analysis Result:\n";
echo "  - Success: " . ($result3['success'] ? 'Yes' : 'No') . "\n";
echo "  - Error: " . ($result3['error'] ?? 'None') . "\n\n";

echo "=== Integration Example ===\n";
echo "To integrate N+1 Detection ML into your application:\n\n";
echo "1. Inject NPlusOneDetectionEngine into your services:\n";
echo "   public function __construct(\n";
echo "       private readonly NPlusOneDetectionEngine \$mlEngine\n";
echo "   ) {}\n\n";
echo "2. Collect query execution data during request processing\n\n";
echo "3. Create QueryExecutionContext from collected queries\n\n";
echo "4. Analyze with ML Engine:\n";
echo "   \$result = \$this->mlEngine->analyzeQueryContext(\$context);\n\n";
echo "5. Take action based on anomalies detected:\n";
echo "   if (\$result['overall_confidence'] > 80.0) {\n";
echo "       \$this->logger->warning('Potential N+1 detected', [\n";
echo "           'anomalies' => count(\$result['anomalies']),\n";
echo "           'confidence' => \$result['overall_confidence'],\n";
echo "       ]);\n";
echo "   }\n\n";

echo "✓ N+1 Detection ML Usage Example Complete\n";
