const express = require('express');
const os = require('os');

const app = express();
const PORT = 3000;

// 记录服务器启动时间
const SERVER_START_TIME = new Date();

// 解析JSON请求体
app.use(express.json());

// GET /api/health - 快速健康检查
app.get('/api/health', (req, res) => {
    res.json({
        status: 'healthy',
        timestamp: new Date().toISOString()
    });
});

// GET /api/status - 详细系统状态
app.get('/api/status', (req, res) => {
    const totalMem = os.totalmem();
    const freeMem = os.freemem();
    const usedMem = totalMem - freeMem;
    
    res.json({
        service: 'HoloLake Health Monitor',
        version: '1.0.0',
        status: 'running',
        timestamp: new Date().toISOString(),
        uptime: {
            seconds: Math.floor((Date.now() - SERVER_START_TIME.getTime()) / 1000),
            startedAt: SERVER_START_TIME.toISOString()
        },
        system: {
            platform: os.platform(),
            arch: os.arch(),
            hostname: os.hostname(),
            nodeVersion: process.version
        },
        memory: {
            totalMB: Math.round(totalMem / 1024 / 1024),
            usedMB: Math.round(usedMem / 1024 / 1024),
            freeMB: Math.round(freeMem / 1024 / 1024),
            usagePercent: Math.round((usedMem / totalMem) * 100) + '%'
        }
    });
});

// POST /api/heartbeat - 心跳上报
let heartbeats = [];
app.post('/api/heartbeat', (req, res) => {
    const heartbeat = {
        timestamp: new Date().toISOString(),
        service: req.body.service || 'unknown',
        status: req.body.status || 'ok'
    };
    heartbeats.push(heartbeat);
    
    res.json({
        received: true,
        heartbeat: heartbeat
    });
});

// GET /api/heartbeat/history - 查看心跳历史
app.get('/api/heartbeat/history', (req, res) => {
    res.json({
        total: heartbeats.length,
        heartbeats: heartbeats.slice(-20)
    });
});

// GET / - 根路径欢迎页
app.get('/', (req, res) => {
    res.json({
        service: 'HoloLake Health Check & Status Report',
        version: '1.0.0',
        endpoints: [
            'GET /api/health - 快速健康检查',
            'GET /api/status - 详细系统状态',
            'POST /api/heartbeat - 心跳上报',
            'GET /api/heartbeat/history - 心跳历史'
        ]
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log('='.repeat(50));
    console.log('🌊 HoloLake Health Check & Status Report');
    console.log('📡 服务运行在: http://localhost:' + PORT);
    console.log('💚 GET /api/health - 健康检查');
    console.log('📊 GET /api/status - 系统状态');
    console.log('💓 POST /api/heartbeat - 心跳上报');
    console.log('='.repeat(50));
});
// ========== 定时自动巡检系统 ==========
const patrolHistory = [];

// 每60秒执行一次巡检
setInterval(() => {
    console.log('[PATROL] 开始定时巡检...');
    
    const totalMem = os.totalmem();
    const freeMem = os.freemem();
    const usedMem = totalMem - freeMem;
    const memPercent = Math.round((usedMem / totalMem) * 100);
    
    const patrolRecord = {
        timestamp: new Date().toISOString(),
        memory: {
            totalMB: Math.round(totalMem / 1024 / 1024),
            usedMB: Math.round(usedMem / 1024 / 1024),
            usagePercent: memPercent
        },
        uptime: Math.floor((Date.now() - SERVER_START_TIME.getTime()) / 1000),
        heartbeatCount: heartbeats.length
    };
    
    patrolHistory.push(patrolRecord);
    
    // 只保留最近50条记录
    if (patrolHistory.length > 50) {
        patrolHistory.shift();
    }
    
    console.log(`[PATROL] 巡检完成 - 内存使用: ${memPercent}%`);
}, 60000); // 60000毫秒 = 60秒

// GET /api/patrol/history - 查看巡检历史
app.get('/api/patrol/history', (req, res) => {
    res.json({
        total: patrolHistory.length,
        patrols: patrolHistory
    });
});

console.log('🔄 定时巡检系统已启动（每60秒）');

// ========== 异常状态告警系统 ==========
const alerts = [];

// 告警检查函数
function checkAlerts(memPercent) {
    let level = null;
    let message = '';
    
    if (memPercent > 90) {
        level = 'critical';
        message = `内存使用率过高: ${memPercent}%`;
    } else if (memPercent > 80) {
        level = 'warning';
        message = `内存使用率警告: ${memPercent}%`;
    }
    
    if (level) {
        const alert = {
            timestamp: new Date().toISOString(),
            level: level,
            message: message,
            memoryPercent: memPercent
        };
        alerts.push(alert);
        
        // 只保留最近20条告警
        if (alerts.length > 20) {
            alerts.shift();
        }
        
        console.log(`[ALERT] ${level.toUpperCase()}: ${message}`);
    }
}

// 修改巡检代码，加入告警检查（找到之前的setInterval，在console.log后面添加）
// 在 patrolHistory.push(patrolRecord); 之后添加：
// checkAlerts(memPercent);

// GET /api/alerts - 查看告警历史
app.get('/api/alerts', (req, res) => {
    res.json({
        total: alerts.length,
        critical: alerts.filter(a => a.level === 'critical').length,
        warning: alerts.filter(a => a.level === 'warning').length,
        alerts: alerts
    });
});

console.log('🚨 异常告警系统已启动（阈值: 80%警告, 90%严重）');
// ========== 心跳超时检测系统 ==========
const HEARTBEAT_TIMEOUT = 5 * 60 * 1000; // 5分钟 = 300000毫秒

// 检查服务在线状态
function checkOnlineStatus() {
    const now = Date.now();
    const onlineServices = [];
    const offlineServices = [];
    
    // 按source分组，找出每个source的最新心跳
    const latestHeartbeats = {};
    heartbeats.forEach(hb => {
        const source = hb.service || 'unknown';
        if (!latestHeartbeats[source] || new Date(hb.timestamp) > new Date(latestHeartbeats[source].timestamp)) {
            latestHeartbeats[source] = hb;
        }
    });
    
    // 检查每个source是否超时
    for (const [source, hb] of Object.entries(latestHeartbeats)) {
        const hbTime = new Date(hb.timestamp).getTime();
        const isOnline = (now - hbTime) < HEARTBEAT_TIMEOUT;
        
        const serviceInfo = {
            source: source,
            lastHeartbeat: hb.timestamp,
            secondsAgo: Math.floor((now - hbTime) / 1000),
            status: isOnline ? 'online' : 'offline'
        };
        
        if (isOnline) {
            onlineServices.push(serviceInfo);
        } else {
            offlineServices.push(serviceInfo);
        }
    }
    
    return { online: onlineServices, offline: offlineServices };
}

// 修改GET /api/status，添加在线服务列表
// 找到原来的 app.get('/api/status', ...)，在res.json里添加：
// services: checkOnlineStatus()

// GET /api/heartbeat/online - 查看在线服务
app.get('/api/heartbeat/online', (req, res) => {
    const status = checkOnlineStatus();
    res.json({
        timestamp: new Date().toISOString(),
        onlineCount: status.online.length,
        offlineCount: status.offline.length,
        online: status.online,
        offline: status.offline
    });
});

console.log('⏰ 心跳超时检测已启动（超时: 5分钟）');
