<?php
/**
 * Weather Server Status Reporter - Debug Version
 * Reports system and service status to portal monitoring database
 */

// Load database config
$dbConfig = require '/var/www/weather-alerts/config/monitoring-db.php';

try {
    $pdo = new PDO(
        "mysql:host={$dbConfig['host']};dbname={$dbConfig['database']}", 
        $dbConfig['username'], 
        $dbConfig['password']
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Ensure system_status record exists
    $stmt = $pdo->prepare("
        INSERT IGNORE INTO system_status (hostname, display_name, ip_address, location, environment, status) 
        VALUES ('weather.datanetwork.tech', 'Weather Alerts Server', '45.33.1.210', 'Linode-Dallas', 'production', 'up')
    ");
    $stmt->execute();

    // Ensure service_status records exist
    $stmt = $pdo->prepare("
        INSERT IGNORE INTO service_status (hostname, service_name, service_type, status) 
        VALUES 
        ('weather.datanetwork.tech', 'NWS Weather Polling', 'weather-api', 'running'),
        ('weather.datanetwork.tech', 'IPAWS Emergency Alerts', 'emergency-api', 'running')
    ");
    $stmt->execute();
    
    // Get system metrics
    $cpu = trim(shell_exec("top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | awk -F'%' '{print $1}'"));
    $memory = trim(shell_exec("free | grep Mem | awk '{printf \"%.2f\", $3/$2 * 100.0}'"));
    $disk = trim(shell_exec("df -h / | awk 'NR==2 {print $5}' | sed 's/%//'"));
    $load = trim(shell_exec("uptime | awk -F'load average:' '{ print $2 }' | awk -F',' '{ print $1 }' | xargs"));
    $uptime = trim(shell_exec("cat /proc/uptime | awk '{ print $1 }'"));
    
    // Clean up metrics (handle potential parsing issues)
    $cpu = floatval($cpu);
    $memory = floatval($memory);
    $disk = floatval($disk);
    $load = floatval($load);
    $uptime = intval(floatval($uptime));
    
    // Update system status
    $stmt = $pdo->prepare("
        UPDATE system_status SET 
            cpu_percent = ?, 
            memory_percent = ?, 
            disk_percent = ?, 
            load_avg = ?, 
            uptime_seconds = ?, 
            status = 'up', 
            last_contact = NOW(),
            updated_at = NOW()
        WHERE hostname = 'weather.datanetwork.tech'
    ");
    $stmt->execute([$cpu, $memory, $disk, $load, $uptime]);
    
    // Check if the record exists
    $check = $pdo->prepare("SELECT hostname FROM system_status WHERE hostname = 'weather.datanetwork.tech'");
    $check->execute();
    echo "Record exists: " . ($check->rowCount() > 0 ? 'YES' : 'NO') . "\n";
    
    // Check weather service status by reading log timestamps
    $currentTime = time();
    
    // Check NWS service
    if (file_exists('/var/www/weather-alerts/logs/last_poll.txt')) {
        $nwsLastPoll = intval(trim(file_get_contents('/var/www/weather-alerts/logs/last_poll.txt')));
        $nwsHealthy = ($currentTime - $nwsLastPoll) < 600; // 10 minutes tolerance
        
        $stmt = $pdo->prepare("
            UPDATE service_status SET 
                status = ?, 
                last_check = NOW()
            WHERE hostname = 'weather.datanetwork.tech' AND service_name = 'NWS Weather Polling'
        ");
        $stmt->execute([$nwsHealthy ? 'running' : 'failed']);
        echo "NWS service UPDATE affected rows: " . $stmt->rowCount() . "\n";
    }
    
    // Check IPAWS service
    if (file_exists('/var/www/weather-alerts/logs/last_ipaws_poll.txt')) {
        $ipawsLastPoll = intval(trim(file_get_contents('/var/www/weather-alerts/logs/last_ipaws_poll.txt')));
        $ipawsHealthy = ($currentTime - $ipawsLastPoll) < 300; // 5 minutes tolerance
        
        $stmt = $pdo->prepare("
            UPDATE service_status SET 
                status = ?, 
                last_check = NOW()
            WHERE hostname = 'weather.datanetwork.tech' AND service_name = 'IPAWS Emergency Alerts'
        ");
        $stmt->execute([$ipawsHealthy ? 'running' : 'failed']);
        echo "IPAWS service UPDATE affected rows: " . $stmt->rowCount() . "\n";
    }
    
    echo "Status reported successfully - CPU: {$cpu}%, Memory: {$memory}%, Disk: {$disk}%\n";
    
} catch (Exception $e) {
    echo "Error reporting status: " . $e->getMessage() . "\n";
    exit(1);
}
?>
