<?php

declare(strict_types=1);

/**
 * Simplified Queue Anomaly Integration Test
 *
 * Tests the ML integration WITHOUT requiring database
 */

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

use App\Framework\Queue\MachineLearning\JobAnomalyDetector;
use App\Framework\Queue\MachineLearning\ValueObjects\JobFeatures;
use App\Framework\Core\ValueObjects\Score;

echo "=== Simplified Queue Anomaly Integration Test ===\n\n";

try {
    // Create detector
    echo "1. Creating JobAnomalyDetector with 40% threshold...\n";
    $detector = new JobAnomalyDetector(
        anomalyThreshold: new Score(0.4),  // 40% threshold
        zScoreThreshold: 3.0,
        iqrMultiplier: 1.5
    );
    echo "   ✓ Detector created\n";
    echo "   Threshold: " . sprintf("%.0f%%", $detector->getThreshold()->value() * 100) . "\n";
    echo "   Configuration: " . json_encode($detector->getConfiguration()) . "\n\n";

    // Test Case 1: Normal Job Features
    echo "2. Test Case 1: Normal Job Execution\n";
    echo "   → Baseline features with low anomaly indicators\n";
    $normalFeatures = new JobFeatures(
        executionTimeVariance: 0.15,      // Low variance
        memoryUsagePattern: 0.10,         // Stable memory
        retryFrequency: 0.0,              // No retries
        failureRate: 0.05,                // 5% failure rate (normal)
        queueDepthCorrelation: 0.10,      // Low queue impact
        dependencyChainComplexity: 0.08,  // Simple
        payloadSizeAnomaly: 0.05,         // Normal payload
        executionTimingRegularity: 0.30   // Moderate regularity
    );

    $result1 = $detector->detect($normalFeatures);
    echo "   Result: " . ($result1->isAnomalous ? "🚨 ANOMALOUS" : "✓ NORMAL") . "\n";
    echo "   Confidence: " . sprintf("%.2f%%", $result1->anomalyScore->value() * 100) . "\n";
    echo "   Severity: {$result1->getSeverity()}\n\n";

    // Test Case 2: High Failure + High Retries
    echo "3. Test Case 2: High Failure Job (Queue System Stress)\n";
    echo "   → Simulating job with high failures and retries\n";
    $highFailureFeatures = new JobFeatures(
        executionTimeVariance: 0.45,      // Moderate variance
        memoryUsagePattern: 0.30,         // Some memory issues
        retryFrequency: 0.85,             // Very high retries (85%)
        failureRate: 0.65,                // High failure rate (65%)
        queueDepthCorrelation: 0.40,      // Queue getting backed up
        dependencyChainComplexity: 0.25,  // Somewhat complex
        payloadSizeAnomaly: 0.20,         // Slightly unusual payload
        executionTimingRegularity: 0.15   // Irregular timing
    );

    $result2 = $detector->detect($highFailureFeatures);
    echo "   Result: " . ($result2->isAnomalous ? "🚨 ANOMALOUS" : "✓ NORMAL") . "\n";
    echo "   Confidence: " . sprintf("%.2f%%", $result2->anomalyScore->value() * 100) . "\n";
    echo "   Severity: {$result2->getSeverity()}\n";
    if ($result2->isAnomalous) {
        echo "   Primary Indicator: {$result2->primaryIndicator}\n";
        echo "   Detected Patterns (" . count($result2->detectedPatterns) . "):\n";
        foreach ($result2->detectedPatterns as $pattern) {
            echo "     - {$pattern['type']}: " . sprintf("%.2f%%", $pattern['confidence']->value() * 100) . "\n";
        }
        echo "   Recommended Action: {$result2->getRecommendedAction()}\n";
        echo "   Requires Immediate Attention: " . ($result2->requiresImmediateAttention() ? "YES" : "NO") . "\n";
    }
    echo "\n";

    // Test Case 3: Performance Degradation
    echo "4. Test Case 3: Performance Degradation\n";
    echo "   → Simulating slow execution with memory issues\n";
    $performanceDegradationFeatures = new JobFeatures(
        executionTimeVariance: 0.85,      // Very unstable execution
        memoryUsagePattern: 0.75,         // Significant memory anomalies
        retryFrequency: 0.25,             // Some retries
        failureRate: 0.20,                // Moderate failure rate
        queueDepthCorrelation: 0.50,      // Queue impact moderate
        dependencyChainComplexity: 0.30,  // Moderate complexity
        payloadSizeAnomaly: 0.35,         // Somewhat unusual payload
        executionTimingRegularity: 0.20   // Irregular
    );

    $result3 = $detector->detect($performanceDegradationFeatures);
    echo "   Result: " . ($result3->isAnomalous ? "🚨 ANOMALOUS" : "✓ NORMAL") . "\n";
    echo "   Confidence: " . sprintf("%.2f%%", $result3->anomalyScore->value() * 100) . "\n";
    echo "   Severity: {$result3->getSeverity()}\n";
    if ($result3->isAnomalous) {
        echo "   Primary Indicator: {$result3->primaryIndicator}\n";
        echo "   Top 3 Contributors:\n";
        foreach ($result3->getTopContributors(3) as $contributor) {
            echo "     - {$contributor['feature']}: " . sprintf("%.2f%%", $contributor['score']->value() * 100) . "\n";
        }
    }
    echo "\n";

    // Test Case 4: Queue Overload (High Queue Depth)
    echo "5. Test Case 4: Queue Overload Scenario\n";
    echo "   → Simulating high queue depth impact\n";
    $queueOverloadFeatures = new JobFeatures(
        executionTimeVariance: 0.50,      // Unstable due to overload
        memoryUsagePattern: 0.45,         // Memory pressure
        retryFrequency: 0.40,             // Many retries
        failureRate: 0.30,                // Elevated failure rate
        queueDepthCorrelation: 0.90,      // VERY high queue depth (900+ jobs!)
        dependencyChainComplexity: 0.35,  // Complex dependencies
        payloadSizeAnomaly: 0.25,         // Normal-ish payload
        executionTimingRegularity: 0.10   // Very irregular due to backlog
    );

    $result4 = $detector->detect($queueOverloadFeatures);
    echo "   Result: " . ($result4->isAnomalous ? "🚨 ANOMALOUS" : "✓ NORMAL") . "\n";
    echo "   Confidence: " . sprintf("%.2f%%", $result4->anomalyScore->value() * 100) . "\n";
    echo "   Severity: {$result4->getSeverity()}\n";
    if ($result4->isAnomalous) {
        echo "   Primary Indicator: {$result4->primaryIndicator}\n";
        echo "   Detected Patterns:\n";
        foreach ($result4->detectedPatterns as $pattern) {
            echo "     - {$pattern['type']}\n";
            echo "       Confidence: " . sprintf("%.2f%%", $pattern['confidence']->value() * 100) . "\n";
            echo "       Description: {$pattern['description']}\n";
        }
    }
    echo "\n";

    // Summary
    echo "=== Test Summary ===\n";
    echo "✓ JobAnomalyDetector: Working correctly\n";
    echo "✓ Threshold Configuration: " . sprintf("%.0f%%", $detector->getThreshold()->value() * 100) . "\n";
    echo "✓ Pattern Detection: Working\n";
    echo "✓ Severity Assessment: Working\n\n";

    echo "Test Results:\n";
    echo "  1. Normal Job: " . ($result1->isAnomalous ? "ANOMALOUS" : "✓ NORMAL") . " (" . sprintf("%.2f%%", $result1->anomalyScore->value() * 100) . ")\n";
    echo "  2. High Failure: " . ($result2->isAnomalous ? "🚨 ANOMALOUS" : "NORMAL") . " (" . sprintf("%.2f%%", $result2->anomalyScore->value() * 100) . ")\n";
    echo "  3. Performance Degradation: " . ($result3->isAnomalous ? "🚨 ANOMALOUS" : "NORMAL") . " (" . sprintf("%.2f%%", $result3->anomalyScore->value() * 100) . ")\n";
    echo "  4. Queue Overload: " . ($result4->isAnomalous ? "🚨 ANOMALOUS" : "NORMAL") . " (" . sprintf("%.2f%%", $result4->anomalyScore->value() * 100) . ")\n\n";

    echo "=== Queue Anomaly Integration Test PASSED ===\n";

} catch (\Throwable $e) {
    echo "\n!!! TEST FAILED !!!\n";
    echo "Error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "\nStack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}
