import { Router } from 'express';
import { authenticateToken } from '../middleware/auth.js';
import net from 'net';
import http from 'http';
import https from 'https';
import { URL } from 'url';
const router = Router();
const networkCheckItems = [
    { id: 'baidu', name: '互联网连接状态', url: 'www.baidu.com', status: 'pending' },
    { id: 'steamworks-api', name: 'Steamworks API(全球)', url: 'api.steampowered.com', status: 'pending' },
    { id: 'steamworks-partner', name: 'Steamworks API（合作/私有）', url: 'partner.steam-api.com', status: 'pending' },
    { id: 'modrinth-api', name: 'Modrinth API', url: 'api.modrinth.com', status: 'pending' },
    { id: 'modrinth-cdn', name: 'Modrinth CDN', url: 'cdn.modrinth.com', status: 'pending' },
    { id: 'mojang-session', name: 'Mojang 会话服务器', url: 'sessionserver.mojang.com', status: 'pending' },
    { id: 'msl-api', name: 'MSL API', url: 'https://api.mslmc.cn/v3', status: 'pending' },
    { id: 'gsm-deploy', name: 'GSManager功能服务', url: 'http://langlangy2.server.xiaozhuhouses.asia', status: 'pending', checkType: 'tcp', port: 44409 },
    { id: 'gsm-mirror', name: '文件边缘下载服务', url: 'download.xiaozhuhouses.asia', status: 'pending', expectedStatusCode: 200 }
];
function tcpPing(host, port, timeout = 10000) {
    return new Promise((resolve) => {
        const startTime = Date.now();
        const socket = new net.Socket();
        const timeoutId = setTimeout(() => {
            socket.destroy();
            resolve({ success: false, error: `连接超时 (${timeout}ms)` });
        }, timeout);
        socket.setTimeout(timeout);
        socket.connect(port, host, () => {
            const responseTime = Date.now() - startTime;
            clearTimeout(timeoutId);
            socket.destroy();
            resolve({ success: true, responseTime });
        });
        socket.on('error', (err) => {
            clearTimeout(timeoutId);
            socket.destroy();
            resolve({ success: false, error: err.message });
        });
        socket.on('timeout', () => {
            clearTimeout(timeoutId);
            socket.destroy();
            resolve({ success: false, error: `连接超时 (${timeout}ms)` });
        });
    });
}
function httpPing(url, timeout = 10000, expectedStatusCode) {
    return new Promise((resolve) => {
        const startTime = Date.now();
        try {
            let parsedUrl;
            if (!url.startsWith('http://') && !url.startsWith('https://')) {
                try {
                    parsedUrl = new URL(`https://${url}`);
                }
                catch {
                    parsedUrl = new URL(`http://${url}`);
                }
            }
            else {
                parsedUrl = new URL(url);
            }
            const protocol = parsedUrl.protocol === 'https:' ? https : http;
            const req = protocol.get(parsedUrl.toString(), {
                timeout,
                headers: {
                    'User-Agent': 'GSManager-NetworkCheck/1.0'
                }
            }, (res) => {
                const responseTime = Date.now() - startTime;
                const statusCode = res.statusCode ?? 0;
                const isStatusValid = expectedStatusCode !== undefined
                    ? statusCode === expectedStatusCode
                    : statusCode >= 200 && statusCode < 300;
                res.resume();
                if (isStatusValid) {
                    resolve({ success: true, responseTime });
                    return;
                }
                const expectedLabel = expectedStatusCode !== undefined
                    ? `，期望 ${expectedStatusCode}`
                    : '，期望 2xx';
                resolve({ success: false, error: `HTTP状态码异常: ${statusCode}${expectedLabel}` });
            });
            req.on('error', (err) => {
                resolve({ success: false, error: err.message });
            });
            req.on('timeout', () => {
                req.destroy();
                resolve({ success: false, error: `连接超时 (${timeout}ms)` });
            });
        }
        catch (error) {
            resolve({ success: false, error: error.message });
        }
    });
}
async function checkUrl(url, timeout = 10000, expectedStatusCode) {
    try {
        if (url.startsWith('http://') || url.startsWith('https://')) {
            return await httpPing(url, timeout, expectedStatusCode);
        }
        const httpResult = await httpPing(url, timeout, expectedStatusCode);
        if (httpResult.success) {
            return httpResult;
        }
        const hostname = url.replace(/^(https?:\/\/)/, '');
        return await tcpPing(hostname, 80, timeout);
    }
    catch (error) {
        return { success: false, error: error.message };
    }
}
function extractHost(target) {
    if (target.startsWith('http://') || target.startsWith('https://')) {
        try {
            return new URL(target).hostname;
        }
        catch {
            return target;
        }
    }
    return target.replace(/^(https?:\/\/)/, '').split('/')[0].split(':')[0];
}
async function checkItem(item, timeout = 10000) {
    if (item.checkType === 'tcp') {
        return tcpPing(extractHost(item.url), item.port ?? 80, timeout);
    }
    if (item.checkType === 'http') {
        return httpPing(item.url, timeout, item.expectedStatusCode);
    }
    return checkUrl(item.url, timeout, item.expectedStatusCode);
}
router.get('/check-all', authenticateToken, async (req, res) => {
    try {
        const results = await Promise.all(networkCheckItems.map(async (item) => {
            const result = await checkItem(item, 10000);
            return {
                id: item.id,
                name: item.name,
                url: item.url,
                status: result.success ? 'success' : 'failed',
                responseTime: result.responseTime,
                error: result.error
            };
        }));
        res.json({
            success: true,
            data: {
                results,
                timestamp: new Date().toISOString()
            }
        });
    }
    catch (error) {
        console.error('网络检测失败:', error);
        res.status(500).json({
            success: false,
            message: '网络检测失败',
            error: error.message
        });
    }
});
router.post('/check-single', authenticateToken, async (req, res) => {
    try {
        const { url, id } = req.body;
        if (!url) {
            return res.status(400).json({
                success: false,
                message: '缺少URL参数'
            });
        }
        const matchedItem = typeof id === 'string'
            ? networkCheckItems.find((item) => item.id === id)
            : undefined;
        const result = matchedItem
            ? await checkItem(matchedItem, 10000)
            : await checkUrl(url, 10000);
        res.json({
            success: true,
            data: {
                id,
                url,
                status: result.success ? 'success' : 'failed',
                responseTime: result.responseTime,
                error: result.error,
                timestamp: new Date().toISOString()
            }
        });
    }
    catch (error) {
        console.error('单项网络检测失败:', error);
        res.status(500).json({
            success: false,
            message: '网络检测失败',
            error: error.message
        });
    }
});
export default router;
