<?php
// lib/Monitor.php
class Monitor {
    private $pdo;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    public function checkSystemHealth() {
        $health = [
            'database' => $this->checkDatabase(),
            'api_keys' => $this->checkApiKeys(),
            'data_freshness' => $this->checkDataFreshness(),
            'disk_space' => $this->checkDiskSpace(),
            'last_errors' => $this->getRecentErrors()
        ];
        
        return $health;
    }
    
    private function checkDatabase() {
        try {
            $stmt = $this->pdo->query("SELECT 1");
            return ['status' => 'healthy', 'message' => 'Database connection OK'];
        } catch (Exception $e) {
            Logger::error('Database health check failed', ['error' => $e->getMessage()]);
            return ['status' => 'error', 'message' => $e->getMessage()];
        }
    }
    
    private function checkApiKeys() {
        $config = require __DIR__ . '/../config.php';
        $status = [];
        
        // Проверка FRED API
        if (!empty($config['fred_api_key'])) {
            $test_url = "https://api.stlouisfed.org/fred/series?series_id=GNPCA&api_key={$config['fred_api_key']}&file_type=json";
            $response = @file_get_contents($test_url);
            $status['fred'] = $response ? 'active' : 'inactive';
        }
        
        return $status;
    }
    
    private function checkDataFreshness() {
        $stmt = $this->pdo->query("SELECT TIMESTAMPDIFF(MINUTE, MAX(timestamp), NOW()) as minutes_ago FROM readings");
        $result = $stmt->fetch();
        
        $minutes_ago = $result['minutes_ago'] ?? 999;
        
        if ($minutes_ago < 65) {
            return ['status' => 'fresh', 'minutes_ago' => $minutes_ago];
        } else {
            Logger::warning('Data freshness check failed', ['minutes_ago' => $minutes_ago]);
            return ['status' => 'stale', 'minutes_ago' => $minutes_ago];
        }
    }
    
    private function checkDiskSpace() {
        $free = disk_free_space(__DIR__);
        $total = disk_total_space(__DIR__);
        $percent_free = ($free / $total) * 100;
        
        return [
            'free_gb' => round($free / (1024*1024*1024), 2),
            'percent_free' => round($percent_free, 1),
            'status' => $percent_free > 10 ? 'healthy' : 'warning'
        ];
    }
    
    private function getRecentErrors() {
        $logs = Logger::getRecentLogs(10);
        return array_filter($logs, function($log) {
            return strpos($log, '[ERROR]') !== false || strpos($log, '[WARNING]') !== false;
        });
    }
}
?>