<?php

declare(strict_types=1);

/**
 * Manual Test for Job Anomaly Detection
 *
 * Tests JobAnomalyDetector with various job behavior patterns
 */

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 "=== Job Anomaly Detection Test ===\n\n";

try {
    // Initialize detector with default thresholds
    $detector = new JobAnomalyDetector(
        anomalyThreshold: new Score(0.5),  // 50% threshold
        zScoreThreshold: 3.0,
        iqrMultiplier: 1.5
    );

    echo "1. Testing Normal Job Behavior (Baseline)\n";
    echo "   → All features at baseline (low values)\n";
    $normalFeatures = new JobFeatures(
        executionTimeVariance: 0.1,      // Low variance
        memoryUsagePattern: 0.1,         // Stable memory
        retryFrequency: 0.0,             // No retries
        failureRate: 0.0,                // No failures
        queueDepthCorrelation: 0.2,      // Low impact
        dependencyChainComplexity: 0.1,  // Simple
        payloadSizeAnomaly: 0.0,         // Normal size
        executionTimingRegularity: 0.3   // Somewhat regular
    );

    $result = $detector->detect($normalFeatures);
    echo "   Result: " . ($result->isAnomalous ? "🚨 ANOMALOUS" : "✓ NORMAL") . "\n";
    echo "   Confidence: " . sprintf("%.2f%%", $result->anomalyScore->value() * 100) . "\n";
    echo "   Risk Level: {$result->getSeverity()}\n";
    if ($result->isAnomalous) {
        echo "   Primary Indicator: {$result->primaryIndicator}\n";
        echo "   Detected Patterns: " . count($result->detectedPatterns) . "\n";
    }
    echo "\n";

    echo "2. Testing High Failure Risk Pattern\n";
    echo "   → High failure rate + frequent retries\n";
    $highFailureFeatures = new JobFeatures(
        executionTimeVariance: 0.3,
        memoryUsagePattern: 0.2,
        retryFrequency: 0.8,             // Very high retries
        failureRate: 0.7,                // High failure rate
        queueDepthCorrelation: 0.3,
        dependencyChainComplexity: 0.2,
        payloadSizeAnomaly: 0.1,
        executionTimingRegularity: 0.2
    );

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

    echo "3. Testing Performance Degradation Pattern\n";
    echo "   → High execution variance + memory issues\n";
    $performanceIssueFeatures = new JobFeatures(
        executionTimeVariance: 0.85,     // Very unstable
        memoryUsagePattern: 0.75,        // Memory anomalies
        retryFrequency: 0.2,
        failureRate: 0.15,
        queueDepthCorrelation: 0.4,
        dependencyChainComplexity: 0.3,
        payloadSizeAnomaly: 0.2,
        executionTimingRegularity: 0.3
    );

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

    echo "4. Testing Bot-like Automated Execution Pattern\n";
    echo "   → Very regular timing + low variance\n";
    $botFeatures = new JobFeatures(
        executionTimeVariance: 0.05,     // Very stable (suspicious)
        memoryUsagePattern: 0.1,
        retryFrequency: 0.0,
        failureRate: 0.0,
        queueDepthCorrelation: 0.1,
        dependencyChainComplexity: 0.1,
        payloadSizeAnomaly: 0.05,
        executionTimingRegularity: 0.95  // Extremely regular (bot-like)
    );

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

    echo "5. Testing Resource Exhaustion Pattern\n";
    echo "   → High queue depth correlation + memory issues\n";
    $resourceExhaustionFeatures = new JobFeatures(
        executionTimeVariance: 0.4,
        memoryUsagePattern: 0.8,         // High memory anomalies
        retryFrequency: 0.3,
        failureRate: 0.25,
        queueDepthCorrelation: 0.85,     // Very high queue impact
        dependencyChainComplexity: 0.5,
        payloadSizeAnomaly: 0.3,
        executionTimingRegularity: 0.2
    );

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

    echo "6. Testing Data Processing Anomaly Pattern\n";
    echo "   → Unusual payload sizes + memory anomalies\n";
    $dataAnomalyFeatures = new JobFeatures(
        executionTimeVariance: 0.3,
        memoryUsagePattern: 0.7,         // Memory issues
        retryFrequency: 0.2,
        failureRate: 0.1,
        queueDepthCorrelation: 0.3,
        dependencyChainComplexity: 0.2,
        payloadSizeAnomaly: 0.9,         // Very unusual payload
        executionTimingRegularity: 0.3
    );

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

    echo "7. Testing Complex Multi-Pattern Anomaly\n";
    echo "   → Multiple issues: high failures + performance + resource issues\n";
    $complexAnomalyFeatures = new JobFeatures(
        executionTimeVariance: 0.75,     // High variance
        memoryUsagePattern: 0.8,         // Memory anomalies
        retryFrequency: 0.6,             // High retries
        failureRate: 0.5,                // High failures
        queueDepthCorrelation: 0.7,      // High queue impact
        dependencyChainComplexity: 0.6,  // Complex dependencies
        payloadSizeAnomaly: 0.5,         // Payload anomalies
        executionTimingRegularity: 0.2
    );

    $result = $detector->detect($complexAnomalyFeatures);
    echo "   Result: " . ($result->isAnomalous ? "🚨 ANOMALOUS" : "✓ NORMAL") . "\n";
    echo "   Confidence: " . sprintf("%.2f%%", $result->anomalyScore->value() * 100) . "\n";
    echo "   Risk Level: {$result->getSeverity()}\n";
    if ($result->isAnomalous) {
        echo "   Primary Indicator: {$result->primaryIndicator}\n";
        echo "   Feature Scores:\n";
        foreach ($result->featureScores as $featureName => $score) {
            if ($score->value() > 0.3) {  // Only show significant scores
                echo "     - {$featureName}: " . sprintf("%.2f%%", $score->value() * 100) . "\n";
            }
        }
        echo "   Detected Patterns:\n";
        foreach ($result->detectedPatterns as $pattern) {
            echo "     - {$pattern['type']}: " . sprintf("%.2f%% confidence", $pattern['confidence']->value() * 100) . "\n";
            echo "       {$pattern['description']}\n";
        }
    }
    echo "\n";

    echo "=== Job Anomaly Detection Test Completed ===\n";
    echo "✓ All test scenarios executed successfully\n";

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