<?php
/**
 * Avatiah OSINT Security Index — Automated Integrity Test
 * Проверяет корректность всех формул, нормализацию, весовую систему и границы AAL.
 * Версия: 1.0
 */

// ==================== ВХОДНЫЕ ДАННЫЕ (тестовые значения) ====================

$data = [
    'brent' => 89,
    'gold' => 999.99,
    'media' => 1666,
    'gov' => 2,
    'cyber' => 2,
    'navy' => 5,
    'diplomatic' => 8,
    'energy' => 55,
    'social' => 3,
];

// Специальный индекс пиццы
$data['pizza_raw'] = 1.0 + ($data['gov'] + ($data['media'] / 1000) + 2) * 0.3;

// ==================== ПАРАМЕТРЫ НОРМАЛИЗАЦИИ ====================

$ranges = [
    'brent' => [50, 500],
    'gold' => [30, 200],
    'media' => [500, 10000],
    'gov' => [1, 4],
    'cyber' => [1, 4],
    'navy' => [1, 5],
    'diplomatic' => [5, 20],
    'energy' => [40, 80],
    'social' => [1, 4],
    'pizza_raw' => [1, 5.2],
];

// ==================== ВЕСА ФАКТОРОВ ====================

$weights = [
    'pizza_raw' => 0.221,
    'brent' => 0.177,
    'media' => 0.133,
    'navy' => 0.106,
    'diplomatic' => 0.088,
    'gov' => 0.071,
    'gold' => 0.062,
    'cyber' => 0.044,
    'energy' => 0.053,
    'social' => 0.044,
];

// ==================== ФУНКЦИИ ====================

function normalize($value, $min, $max) {
    $score = ($value - $min) / ($max - $min) * 10;
    return max(0, min(10, round($score, 2)));
}

function calculateSecurityIndex($data, $ranges, $weights) {
    $totalWeight = array_sum($weights);
    $index = 0;
    $scores = [];
    foreach ($data as $k => $v) {
        [$min, $max] = $ranges[$k];
        $score = normalize($v, $min, $max);
        $scores[$k] = $score;
        $index += $score * ($weights[$k] / $totalWeight);
    }
    return [$index, $scores];
}

function aalLevel($index) {
    if ($index < 2) return "AAL-5 (Норма)";
    if ($index < 3.5) return "AAL-4 (Повышенная нужда)";
    if ($index < 5) return "AAL-3 (Усиление наблюдения)";
    if ($index < 7) return "AAL-2 (Критическая готовность)";
    return "AAL-1 (Чрезвычайная угроза)";
}

function metrics($index) {
    return [
        'time_to_aa3_days' => round(max(0.5, min(7.0, 7.0 - $index)), 2),
        'signal_detection_hours' => round(max(6, min(72, 72 - ($index * 8))), 2),
        'reaction_hours' => round(max(1, min(24, 24 - ($index * 3))), 2),
    ];
}

// ==================== ВЫПОЛНЕНИЕ ТЕСТА ====================

[$index, $scores] = calculateSecurityIndex($data, $ranges, $weights);
$aal = aalLevel($index);
$m = metrics($index);

// ==================== ВЫВОД ====================

echo "=== Avatiah OSINT Integrity Test ===\n\n";
echo "Scores:\n";
foreach ($scores as $k => $v) {
    echo str_pad($k, 15) . ": " . str_pad($v, 5, ' ', STR_PAD_LEFT) . "\n";
}

echo "\nSecurity Index: " . round($index, 3) . "\n";
echo "AAL Level: $aal\n\n";

echo "Derived Metrics:\n";
echo "- Time to AA-3: {$m['time_to_aa3_days']} days\n";
echo "- Signal Detection: {$m['signal_detection_hours']} hours\n";
echo "- Reaction Time: {$m['reaction_hours']} hours\n";

// ==================== АВТОМАТИЧЕСКИЕ ПРОВЕРКИ ====================

echo "\nChecks:\n";
$errors = 0;

if ($index < 0 || $index > 10) {
    echo "❌ Security Index out of bounds (0–10)\n";
    $errors++;
}
foreach ($scores as $k => $v) {
    if ($v < 0 || $v > 10) {
        echo "❌ $k score out of bounds\n";
        $errors++;
    }
}
if ($errors === 0) echo "✅ All tests passed successfully!\n";
else echo "⚠️ Total errors: $errors\n";

?>
