<?php
// /api/realtime.php — СВЕЖИЕ ДАННЫЕ В РЕАЛЬНОМ ВРЕМЕНИ
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../lib/DataSources.php';
$config = require __DIR__ . '/../config.php';

try {
    $factors = ['pizza', 'oil', 'media', 'navy', 'vip', 'gov', 'gold', 'cyber', 'energy', 'social'];
    $raw_values = [];
    $scores = [];
    foreach ($factors as $factor) {
        $raw = DataSources::getValue($factor, $config);
        $raw_values[$factor] = $raw ?? 0;
        $scores[$factor] = DataSources::normalize($factor, $raw_values[$factor]);
    }

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

    // Форматируем компоненты
    $components = [];
    foreach ($factors as $factor) {
        $components[$factor] = [
            'raw' => (float)$raw_values[$factor],
            'score' => (float)$scores[$factor]
        ];
    }

    echo json_encode([
        'security_index' => (float)$index,
        'aal_level' => (int)$aal,
        'timestamp' => date('c'),
        'is_manual' => false,
        'components' => $components,
        'time_to_aa3' => $metrics['time_to_aa3'],
        'signal_detection_time' => $metrics['signal_detection_time'],
        'detection_to_action_time' => $metrics['detection_to_action_time']
    ]);

} catch (Exception $e) {
    http_response_code(500);
    error_log("API realtime error: " . $e->getMessage());
    echo json_encode(['error' => 'Service unavailable']);
}
?>