<?php
// api/latest.php — Умная система с авто-обновлением БД
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Cache-Control: no-cache, must-revalidate');

require_once __DIR__ . '/../config.php';

try {
    $config = require __DIR__ . '/../config.php';
    
    // === ПРОВЕРКА СВЕЖЕСТИ ДАННЫХ ===
    $updateInterval = 900; // 15 минут
    $lastCollectorFile = __DIR__ . '/../cache/last_collector_run.txt';
    $needsUpdate = false;
    
    if (!file_exists($lastCollectorFile)) {
        $needsUpdate = true;
    } else {
        $lastRun = (int)file_get_contents($lastCollectorFile);
        $timeSinceLastRun = time() - $lastRun;
        
        if ($timeSinceLastRun >= $updateInterval) {
            $needsUpdate = true;
        }
    }
    
    // === АВТОМАТИЧЕСКИЙ ЗАПУСК COLLECTOR ===
    if ($needsUpdate) {
        // Создаём lock-файл чтобы избежать параллельных запусков
        $lockFile = __DIR__ . '/../cache/collector.lock';
        
        if (!file_exists($lockFile)) {
            // Создаём lock
            @mkdir(dirname($lockFile), 0755, true);
            file_put_contents($lockFile, time());
            
            // Запускаем collector в фоне (не блокируем ответ пользователю)
            $collectorPath = __DIR__ . '/../collector.php';
            
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                // Windows
                pclose(popen("start /B php \"$collectorPath\" > NUL 2>&1", "r"));
            } else {
                // Linux/Unix
                exec("php \"$collectorPath\" > /dev/null 2>&1 &");
            }
            
            // Обновляем время последнего запуска
            file_put_contents($lastCollectorFile, time());
            
            // Даём collector 2 секунды на запуск
            sleep(2);
            
            // Удаляем lock
            @unlink($lockFile);
        }
    }
    
    // === ПОДКЛЮЧЕНИЕ К БД ===
    $pdo = new PDO(
        "mysql:host={$config['db_host']};dbname={$config['db_name']};charset=utf8mb4",
        $config['db_user'],
        $config['db_pass'],
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );

    // === ПОЛУЧЕНИЕ ПОСЛЕДНИХ ДАННЫХ ===
    $stmt = $pdo->query("
        SELECT * 
        FROM readings 
        ORDER BY timestamp DESC 
        LIMIT 1
    ");
    
    $record = $stmt->fetch();
    
    // === ЕСЛИ ДАННЫХ НЕТ - ЗАПУСКАЕМ COLLECTOR СИНХРОННО ===
    if (!$record) {
        // Первый запуск - выполняем синхронно
        require_once __DIR__ . '/../lib/Logger.php';
        require_once __DIR__ . '/../lib/DataSources.php';
        
        // Собираем данные
        $factors = ['pizza','oil','media','navy','vip','gov','gold','cyber','energy','social','mfa','pm','contractors','darknet','medical','satellite','evacuation','reserves'];
        $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);

        // Вставляем в БД
        $columns = [];
        $placeholders = [];
        $values = [];

        foreach ($factors as $f) {
            $columns[] = "{$f}_raw";
            $columns[] = "{$f}_score";
            $placeholders[] = ":{$f}_raw";
            $placeholders[] = ":{$f}_score";
            $values[":{$f}_raw"] = $raw_values[$f];
            $values[":{$f}_score"] = $scores[$f];
        }

        $columns = array_merge($columns, [
            'security_index', 'aal_level', 'is_manual',
            'time_to_aa3', 'signal_detection_time', 'detection_to_action_time'
        ]);
        $placeholders = array_merge($placeholders, [
            ':security_index', ':aal_level', '0',
            ':time_to_aa3', ':signal_detection_time', ':detection_to_action_time'
        ]);
        $values[':security_index'] = $index;
        $values[':aal_level'] = $aal;
        $values[':time_to_aa3'] = $metrics['time_to_aa3'];
        $values[':signal_detection_time'] = $metrics['signal_detection_time'];
        $values[':detection_to_action_time'] = $metrics['detection_to_action_time'];

        $sql = "INSERT INTO readings (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($values);
        
        // Получаем только что вставленную запись
        $record = $pdo->query("SELECT * FROM readings ORDER BY timestamp DESC LIMIT 1")->fetch();
        
        file_put_contents($lastCollectorFile, time());
    }
    
    // === ФОРМИРОВАНИЕ ОТВЕТА ===
    $dataAge = time() - strtotime($record['timestamp']);
    
    $response = [
        'success' => true,
        'timestamp' => $record['timestamp'],
        'security_index' => round((float)$record['security_index'], 1),
        'aal_level' => (int)$record['aal_level'],
        'is_manual' => (bool)$record['is_manual'],
        'manual_reason' => $record['manual_reason'] ?? null,
        
        // Метрики
        'time_to_aa3' => $record['time_to_aa3'] !== null ? round((float)$record['time_to_aa3'], 1) : null,
        'signal_detection_time' => $record['signal_detection_time'] !== null ? (int)$record['signal_detection_time'] : null,
        'detection_to_action_time' => $record['detection_to_action_time'] !== null ? (int)$record['detection_to_action_time'] : null,
        
        // Компоненты (все 18 факторов)
        'components' => [
            'pizza' => [
                'raw' => round((float)$record['pizza_raw'], 2),
                'score' => round((float)$record['pizza_score'], 2)
            ],
            'oil' => [
                'raw' => round((float)$record['oil_raw'], 2),
                'score' => round((float)$record['oil_score'], 2)
            ],
            'media' => [
                'raw' => round((float)$record['media_raw'], 0),
                'score' => round((float)$record['media_score'], 2)
            ],
            'navy' => [
                'raw' => round((float)$record['navy_raw'], 0),
                'score' => round((float)$record['navy_score'], 2)
            ],
            'vip' => [
                'raw' => round((float)$record['vip_raw'], 0),
                'score' => round((float)$record['vip_score'], 2)
            ],
            'gov' => [
                'raw' => round((float)$record['gov_raw'], 0),
                'score' => round((float)$record['gov_score'], 2)
            ],
            'gold' => [
                'raw' => round((float)$record['gold_raw'], 2),
                'score' => round((float)$record['gold_score'], 2)
            ],
            'cyber' => [
                'raw' => round((float)$record['cyber_raw'], 0),
                'score' => round((float)$record['cyber_score'], 2)
            ],
            'energy' => [
                'raw' => round((float)$record['energy_raw'], 2),
                'score' => round((float)$record['energy_score'], 2)
            ],
            'social' => [
                'raw' => round((float)$record['social_raw'], 0),
                'score' => round((float)$record['social_score'], 2)
            ],
            'mfa' => [
                'raw' => round((float)$record['mfa_raw'], 0),
                'score' => round((float)$record['mfa_score'], 2)
            ],
            'pm' => [
                'raw' => round((float)$record['pm_raw'], 0),
                'score' => round((float)$record['pm_score'], 2)
            ],
            'contractors' => [
                'raw' => round((float)$record['contractors_raw'], 0),
                'score' => round((float)$record['contractors_score'], 2)
            ],
            'darknet' => [
                'raw' => round((float)$record['darknet_raw'], 0),
                'score' => round((float)$record['darknet_score'], 2)
            ],
            'medical' => [
                'raw' => round((float)$record['medical_raw'], 0),
                'score' => round((float)$record['medical_score'], 2)
            ],
            'satellite' => [
                'raw' => round((float)$record['satellite_raw'], 0),
                'score' => round((float)$record['satellite_score'], 2)
            ],
            'evacuation' => [
                'raw' => round((float)$record['evacuation_raw'], 0),
                'score' => round((float)$record['evacuation_score'], 2)
            ],
            'reserves' => [
                'raw' => round((float)$record['reserves_raw'], 0),
                'score' => round((float)$record['reserves_score'], 2)
            ]
        ],
        
        // Метаданные
        'data_age_seconds' => $dataAge,
        'data_age_minutes' => round($dataAge / 60, 1),
        'next_update_in_seconds' => max(0, $updateInterval - $dataAge),
        'auto_update_enabled' => true,
        'update_interval_seconds' => $updateInterval
    ];

    // Предупреждение если данные устарели
    if ($dataAge > 1800) { // Старше 30 минут
        $response['warning'] = 'Data is outdated. Auto-update may have failed.';
    }

    // Индикатор качества данных
    if ($dataAge < 300) {
        $response['data_quality'] = 'excellent';
    } elseif ($dataAge < 900) {
        $response['data_quality'] = 'good';
    } elseif ($dataAge < 1800) {
        $response['data_quality'] = 'acceptable';
    } else {
        $response['data_quality'] = 'poor';
    }

    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Database error',
        'message' => 'Could not connect to database',
        'details' => $e->getMessage()
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Server error',
        'message' => $e->getMessage()
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
?>