<?php
require_once 'lib/DataSources.php';
require_once 'config.php';

header('Content-Type: text/plain; charset=utf-8');

echo "=== ДЕБАГ РАСЧЕТА ИНДЕКСА БЕЗОПАСНОСТИ ===\n\n";

// Все факторы из директории
$factors = ['oil','media','navy','vip','gov','gold','cyber','energy','social','mfa','pm','contractors','darknet','medical','satellite','evacuation','reserves'];

$raw_values = [];
$scores = [];

echo "📊 СЫРЫЕ ДАННЫХ И РАСЧЕТЫ:\n";
echo str_repeat("-", 80) . "\n";

foreach ($factors as $factor) {
    $raw = DataSources::getValue($factor, $config);
    $score = DataSources::normalize($factor, $raw);
    
    $raw_values[$factor] = $raw;
    $scores[$factor] = $score;
    
    printf("%-15s: raw=%-8.2f score=%-6.2f range=%s\n", 
        $factor, $raw, $score, 
        json_encode(DataSources::$ranges[$factor] ?? 'N/A')
    );
}

echo "\n⚖️ ВЕСА ФАКТОРОВ:\n";
echo str_repeat("-", 80) . "\n";

$total_weight = 0;
foreach ($factors as $factor) {
    $weight = DataSources::$weights[$factor] ?? 0;
    $total_weight += $weight;
    printf("%-15s: %.3f (%.1f%%)\n", $factor, $weight, $weight * 100);
}
printf("ОБЩИЙ ВЕС: %.3f\n", $total_weight);

echo "\n🧮 РАСЧЕТ ИНДЕКСА:\n";
echo str_repeat("-", 80) . "\n";

$result = DataSources::calculateIndex($scores);
$index = $result['index'];
$aal = $result['aal'];

$calculated_index = 0;
foreach ($factors as $factor) {
    $weight = DataSources::$weights[$factor] ?? 0;
    $score = $scores[$factor];
    $contribution = $score * ($weight / $total_weight);
    $calculated_index += $contribution;
    
    printf("%-15s: %.2f × (%.3f/%.3f) = %.4f\n", 
        $factor, $score, $weight, $total_weight, $contribution
    );
}

printf("\n📈 ИТОГОВЫЙ ИНДЕКС: %.3f\n", $calculated_index);
printf("🎯 AAL УРОВЕНЬ: %d\n", $aal);
printf("🔢 ОФИЦИАЛЬНЫЙ РАСЧЕТ: %.3f (AAL %d)\n", $index, $aal);

// Проверим данные из БД
echo "\n🗄️ ДАННЫЕ ИЗ БАЗЫ ДАННЫХ:\n";
echo str_repeat("-", 80) . "\n";

try {
    $pdo = new PDO(
        "mysql:host={$config['db_host']};dbname={$config['db_name']};charset=utf8mb4",
        $config['db_user'],
        $config['db_pass']
    );
    
    $stmt = $pdo->query("SELECT security_index, aal_level, timestamp FROM readings ORDER BY timestamp DESC LIMIT 1");
    $db_data = $stmt->fetch();
    
    if ($db_data) {
        printf("Индекс из БД: %.3f\n", $db_data['security_index']);
        printf("AAL из БД: %d\n", $db_data['aal_level']);
        printf("Время: %s\n", $db_data['timestamp']);
    } else {
        echo "В БД нет данных\n";
    }
} catch (Exception $e) {
    echo "Ошибка БД: " . $e->getMessage() . "\n";
}
?>