import { Router } from 'express';
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { deployTModLoaderServer, deployFactorioServer, cancelDeployment, getActiveDeployments, getTModLoaderInfo, searchMrpackModpacks, getMrpackProjectVersions, deployMrpackServer, deployBedrockServer, getBedrockDownloadLinks } from '../modules/game/othergame/unified-functions.js';
import { authenticateToken } from '../middleware/auth.js';
import logger from '../utils/logger.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const router = Router();
let io;
export function setMoreGamesDependencies(socketIO) {
    io = socketIO;
}
export var GameType;
(function (GameType) {
    GameType["TMODLOADER"] = "tmodloader";
    GameType["FACTORIO"] = "factorio";
    GameType["MRPACK"] = "mrpack";
    GameType["BEDROCK"] = "bedrock";
})(GameType || (GameType = {}));
export var Platform;
(function (Platform) {
    Platform["WINDOWS"] = "windows";
    Platform["LINUX"] = "linux";
    Platform["MACOS"] = "macos";
})(Platform || (Platform = {}));
function getCurrentPlatform() {
    const platform = process.platform;
    switch (platform) {
        case 'win32':
            return Platform.WINDOWS;
        case 'linux':
            return Platform.LINUX;
        case 'darwin':
            return Platform.MACOS;
        default:
            return Platform.LINUX;
    }
}
function isGameSupportedOnCurrentPlatform(game) {
    const currentPlatform = getCurrentPlatform();
    return game.supportedPlatforms.includes(currentPlatform);
}
const supportedGames = [
    {
        id: 'tmodloader',
        name: 'tModLoader',
        description: 'Terraria模组加载器服务端',
        icon: '🎮',
        category: '沙盒游戏',
        supported: true,
        supportedPlatforms: [Platform.WINDOWS, Platform.LINUX, Platform.MACOS]
    },
    {
        id: 'factorio',
        name: 'Factorio',
        description: 'Factorio工厂建造游戏服务端',
        icon: '🏭',
        category: '策略游戏',
        supported: true,
        supportedPlatforms: [Platform.LINUX]
    },
    {
        id: 'bedrock',
        name: 'Minecraft基岩版',
        description: 'Minecraft基岩版官方服务端',
        icon: '⛏️',
        category: '沙盒游戏',
        supported: true,
        supportedPlatforms: [Platform.WINDOWS, Platform.LINUX]
    }
];
router.get('/active-deployments', authenticateToken, async (req, res) => {
    try {
        const activeDeployments = getActiveDeployments();
        res.json({
            success: true,
            data: activeDeployments.map(deployment => ({
                id: deployment.id,
                game: deployment.game,
                targetDirectory: deployment.targetDirectory,
                startTime: deployment.startTime
            })),
            message: '获取活动部署列表成功'
        });
    }
    catch (error) {
        logger.error('获取活动部署列表失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取活动部署列表失败'
        });
    }
});
router.post('/cancel-deployment', authenticateToken, async (req, res) => {
    try {
        const { deploymentId } = req.body;
        if (!deploymentId) {
            return res.status(400).json({
                success: false,
                message: '缺少部署ID参数'
            });
        }
        const activeDeployments = getActiveDeployments();
        logger.info(`尝试取消部署: ${deploymentId}`, {
            deploymentId,
            activeDeployments: activeDeployments.map(d => ({
                id: d.id,
                game: d.game,
                startTime: d.startTime
            }))
        });
        const success = await cancelDeployment(deploymentId);
        if (!success) {
            return res.status(404).json({
                success: false,
                message: '未找到指定的部署任务或取消失败',
                debug: {
                    requestedId: deploymentId,
                    activeDeployments: activeDeployments.map(d => d.id)
                }
            });
        }
        logger.info(`部署任务已取消: ${deploymentId}`);
        res.json({
            success: true,
            message: '部署已取消'
        });
    }
    catch (error) {
        logger.error('取消部署失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '取消部署失败'
        });
    }
});
router.get('/games', authenticateToken, async (req, res) => {
    try {
        const currentPlatform = getCurrentPlatform();
        const filteredGames = supportedGames.map(game => ({
            ...game,
            currentPlatform,
            supportedOnCurrentPlatform: isGameSupportedOnCurrentPlatform(game)
        }));
        res.json({
            success: true,
            data: filteredGames,
            meta: {
                currentPlatform,
                totalGames: supportedGames.length,
                supportedGames: filteredGames.filter(g => g.supportedOnCurrentPlatform).length
            }
        });
    }
    catch (error) {
        logger.error('获取游戏列表失败:', error);
        res.status(500).json({
            success: false,
            error: '获取游戏列表失败',
            message: error.message
        });
    }
});
router.get('/games/:gameId', authenticateToken, async (req, res) => {
    try {
        const { gameId } = req.params;
        const game = supportedGames.find(g => g.id === gameId);
        if (!game) {
            return res.status(404).json({
                success: false,
                error: '游戏不存在',
                message: `未找到游戏: ${gameId}`
            });
        }
        res.json({
            success: true,
            data: game
        });
    }
    catch (error) {
        logger.error('获取游戏信息失败:', error);
        res.status(500).json({
            success: false,
            error: '获取游戏信息失败',
            message: error.message
        });
    }
});
router.post('/deploy/tmodloader', authenticateToken, async (req, res) => {
    try {
        const { installPath, options = {}, socketId } = req.body;
        if (!installPath) {
            return res.status(400).json({
                success: false,
                error: '缺少必填参数',
                message: '安装路径为必填项'
            });
        }
        const deploymentId = `tmodloader-deploy-${Date.now()}`;
        res.json({
            success: true,
            data: {
                deploymentId
            },
            message: '开始部署tModLoader服务端'
        });
        logger.info('开始部署tModLoader服务端', { installPath, options, deploymentId });
        (async () => {
            try {
                const result = await deployTModLoaderServer({
                    targetDirectory: installPath,
                    options,
                    deploymentId,
                    onProgress: (message, type = 'info') => {
                        if (io && socketId) {
                            io.to(socketId).emit('more-games-deploy-log', {
                                deploymentId,
                                message,
                                type,
                                timestamp: new Date().toISOString()
                            });
                        }
                    }
                });
                if (result.success) {
                    logger.info('tModLoader服务端部署成功', {
                        installPath: result.targetDirectory,
                        deploymentId: result.deploymentId
                    });
                    if (io && socketId) {
                        io.to(socketId).emit('more-games-deploy-log', {
                            deploymentId,
                            message: 'tModLoader服务端部署成功！'
                        });
                        io.to(socketId).emit('more-games-deploy-progress', {
                            deploymentId,
                            progress: { percentage: 100 },
                            message: '部署完成'
                        });
                        io.to(socketId).emit('more-games-deploy-complete', {
                            deploymentId,
                            success: true,
                            data: {
                                installPath: result.targetDirectory,
                                deploymentId: result.deploymentId
                            },
                            message: 'tModLoader服务端部署成功！'
                        });
                    }
                }
                else {
                    logger.error('tModLoader部署失败:', result.message);
                    if (io && socketId) {
                        io.to(socketId).emit('more-games-deploy-error', {
                            deploymentId,
                            success: false,
                            error: result.message || 'tModLoader部署失败'
                        });
                    }
                }
            }
            catch (error) {
                logger.error('tModLoader部署失败:', error);
                if (io && socketId) {
                    io.to(socketId).emit('more-games-deploy-error', {
                        deploymentId,
                        success: false,
                        error: error.message || 'tModLoader部署失败'
                    });
                }
            }
        })();
    }
    catch (error) {
        logger.error('启动tModLoader部署失败:', error);
        res.status(500).json({
            success: false,
            error: 'tModLoader部署失败',
            message: error.message
        });
    }
});
router.post('/deploy/factorio', authenticateToken, async (req, res) => {
    try {
        const { installPath, options = {}, socketId } = req.body;
        if (!installPath) {
            return res.status(400).json({
                success: false,
                error: '缺少必填参数',
                message: '安装路径为必填项'
            });
        }
        const deploymentId = `factorio-deploy-${Date.now()}`;
        res.json({
            success: true,
            data: {
                deploymentId
            },
            message: '开始部署Factorio服务端'
        });
        logger.info('开始部署Factorio服务端', { installPath, options, deploymentId });
        (async () => {
            try {
                const result = await deployFactorioServer({
                    targetDirectory: installPath,
                    deploymentId,
                    onProgress: (message, type = 'info') => {
                        if (io && socketId) {
                            io.to(socketId).emit('more-games-deploy-log', {
                                deploymentId,
                                message,
                                type,
                                timestamp: new Date().toISOString()
                            });
                        }
                    }
                });
                if (result.success) {
                    logger.info('Factorio服务端部署成功', {
                        installPath: result.targetDirectory,
                        deploymentId: result.deploymentId
                    });
                    if (io && socketId) {
                        io.to(socketId).emit('more-games-deploy-log', {
                            deploymentId,
                            message: 'Factorio服务端部署成功！'
                        });
                        io.to(socketId).emit('more-games-deploy-progress', {
                            deploymentId,
                            progress: { percentage: 100 },
                            message: '部署完成'
                        });
                        io.to(socketId).emit('more-games-deploy-complete', {
                            deploymentId,
                            success: true,
                            data: {
                                installPath: result.targetDirectory,
                                deploymentId: result.deploymentId
                            },
                            message: 'Factorio服务端部署成功！'
                        });
                    }
                }
                else {
                    logger.error('Factorio部署失败:', result.message);
                    if (io && socketId) {
                        io.to(socketId).emit('more-games-deploy-error', {
                            deploymentId,
                            success: false,
                            error: result.message || 'Factorio部署失败'
                        });
                    }
                }
            }
            catch (error) {
                logger.error('Factorio部署失败:', error);
                if (io && socketId) {
                    io.to(socketId).emit('more-games-deploy-error', {
                        deploymentId,
                        success: false,
                        error: error.message || 'Factorio部署失败'
                    });
                }
            }
        })();
    }
    catch (error) {
        logger.error('启动Factorio部署失败:', error);
        res.status(500).json({
            success: false,
            error: 'Factorio部署失败',
            message: error.message
        });
    }
});
router.get('/status/:gameId/:installPath(*)', authenticateToken, async (req, res) => {
    try {
        const { gameId, installPath } = req.params;
        if (!installPath) {
            return res.status(400).json({
                success: false,
                error: '缺少必填参数',
                message: '安装路径为必填项'
            });
        }
        let isDeployed = false;
        let version = null;
        switch (gameId) {
            case 'tmodloader': {
                const tmodloaderPath = path.join(installPath, 'tModLoaderServer.exe');
                try {
                    await fs.access(tmodloaderPath);
                    isDeployed = true;
                }
                catch {
                    isDeployed = false;
                }
                break;
            }
            case 'factorio': {
                const factorioExecutable = path.join(installPath, 'factorio', 'bin', 'x64', 'factorio');
                try {
                    await fs.access(factorioExecutable);
                    isDeployed = true;
                }
                catch {
                    isDeployed = false;
                }
                break;
            }
            default:
                return res.status(400).json({
                    success: false,
                    error: '不支持的游戏类型',
                    message: `不支持的游戏: ${gameId}`
                });
        }
        res.json({
            success: true,
            data: {
                gameId,
                installPath,
                isDeployed,
                version
            }
        });
    }
    catch (error) {
        logger.error('检查部署状态失败:', error);
        res.status(500).json({
            success: false,
            error: '检查部署状态失败',
            message: error.message
        });
    }
});
router.get('/version/:gameId', authenticateToken, async (req, res) => {
    try {
        const { gameId } = req.params;
        let versionInfo = null;
        switch (gameId) {
            case 'tmodloader': {
                versionInfo = await getTModLoaderInfo();
                break;
            }
            case 'factorio': {
                versionInfo = {
                    version: 'latest',
                    downloadUrl: 'https://factorio.com/get-download/stable/headless/linux64'
                };
                break;
            }
            default:
                return res.status(400).json({
                    success: false,
                    error: '不支持的游戏类型',
                    message: `不支持的游戏: ${gameId}`
                });
        }
        res.json({
            success: true,
            data: versionInfo
        });
    }
    catch (error) {
        logger.error('获取版本信息失败:', error);
        res.status(500).json({
            success: false,
            error: '获取版本信息失败',
            message: error.message
        });
    }
});
router.get('/mrpack/search', authenticateToken, async (req, res) => {
    try {
        const { query, limit = 20, offset = 0, categories, versions, loaders } = req.query;
        const searchOptions = {
            query: query,
            limit: parseInt(limit),
            offset: parseInt(offset),
            categories: categories ? categories.split(',') : undefined,
            versions: versions ? versions.split(',') : undefined,
            loaders: loaders ? loaders.split(',') : undefined
        };
        const result = await searchMrpackModpacks(searchOptions);
        res.json({
            success: true,
            data: result,
            message: '搜索整合包成功'
        });
    }
    catch (error) {
        logger.error('搜索整合包失败:', error);
        res.status(500).json({
            success: false,
            error: '搜索整合包失败',
            message: error.message
        });
    }
});
router.get('/mrpack/project/:projectId/versions', authenticateToken, async (req, res) => {
    try {
        const { projectId } = req.params;
        if (!projectId) {
            return res.status(400).json({
                success: false,
                error: '缺少项目ID参数',
                message: '项目ID为必填项'
            });
        }
        const versions = await getMrpackProjectVersions(projectId);
        res.json({
            success: true,
            data: versions,
            message: '获取项目版本成功'
        });
    }
    catch (error) {
        logger.error('获取项目版本失败:', error);
        res.status(500).json({
            success: false,
            error: '获取项目版本失败',
            message: error.message
        });
    }
});
router.post('/deploy/mrpack', authenticateToken, async (req, res) => {
    try {
        const { projectId, versionId, installPath, options = {}, socketId } = req.body;
        if (!projectId || !versionId || !installPath) {
            return res.status(400).json({
                success: false,
                error: '缺少必填参数',
                message: 'projectId、versionId和installPath为必填项'
            });
        }
        if (typeof projectId !== 'string' || typeof versionId !== 'string' || typeof installPath !== 'string') {
            return res.status(400).json({
                success: false,
                error: '参数类型错误',
                message: 'projectId、versionId和installPath必须是字符串类型'
            });
        }
        if (versionId.length < 8 || !/^[a-zA-Z0-9]+$/.test(versionId)) {
            return res.status(400).json({
                success: false,
                error: '版本ID格式错误',
                message: `无效的版本ID: ${versionId}。版本ID应该是至少8位的字母数字字符串。`
            });
        }
        const deploymentId = `mrpack-deploy-${Date.now()}`;
        res.json({
            success: true,
            data: {
                deploymentId
            },
            message: '开始部署Minecraft整合包'
        });
        logger.info('开始部署Minecraft整合包', { projectId, versionId, installPath, options, deploymentId });
        (async () => {
            try {
                const result = await deployMrpackServer({
                    projectId,
                    versionId,
                    targetDirectory: installPath,
                    deploymentId,
                    options,
                    onProgress: (message, type = 'info') => {
                        if (io && socketId) {
                            io.to(socketId).emit('more-games-deploy-log', {
                                deploymentId,
                                message,
                                type,
                                timestamp: new Date().toISOString()
                            });
                        }
                    }
                });
                if (result.success) {
                    logger.info('Minecraft整合包部署成功', {
                        installPath: result.targetDirectory,
                        deploymentId: result.deploymentId
                    });
                    if (io && socketId) {
                        io.to(socketId).emit('more-games-deploy-log', {
                            deploymentId,
                            message: 'Minecraft整合包部署成功！'
                        });
                        io.to(socketId).emit('more-games-deploy-progress', {
                            deploymentId,
                            progress: { percentage: 100 },
                            message: '部署完成'
                        });
                        io.to(socketId).emit('more-games-deploy-complete', {
                            deploymentId,
                            success: true,
                            data: {
                                installPath: result.targetDirectory,
                                deploymentId: result.deploymentId
                            },
                            message: 'Minecraft整合包部署成功！'
                        });
                    }
                }
                else {
                    logger.error('Minecraft整合包部署失败:', result.message);
                    if (io && socketId) {
                        io.to(socketId).emit('more-games-deploy-error', {
                            deploymentId,
                            success: false,
                            error: result.message || 'Minecraft整合包部署失败'
                        });
                    }
                }
            }
            catch (error) {
                logger.error('Minecraft整合包部署失败:', error);
                if (io && socketId) {
                    io.to(socketId).emit('more-games-deploy-error', {
                        deploymentId,
                        success: false,
                        error: error.message || 'Minecraft整合包部署失败'
                    });
                }
            }
        })();
    }
    catch (error) {
        logger.error('启动Minecraft整合包部署失败:', error);
        res.status(500).json({
            success: false,
            error: 'Minecraft整合包部署失败',
            message: error.message
        });
    }
});
router.get('/bedrock/download-links', authenticateToken, async (req, res) => {
    try {
        logger.info('开始获取Minecraft基岩版下载链接');
        const versionInfo = await getBedrockDownloadLinks();
        logger.info('成功获取Minecraft基岩版下载链接', {
            linksCount: versionInfo.links.length
        });
        res.json({
            success: true,
            data: versionInfo,
            message: '获取下载链接成功'
        });
    }
    catch (error) {
        logger.error('获取Minecraft基岩版下载链接失败:', error);
        res.status(500).json({
            success: false,
            error: '获取下载链接失败',
            message: error.message
        });
    }
});
router.post('/deploy/bedrock', authenticateToken, async (req, res) => {
    try {
        const { installPath, platform, versionType = 'stable', socketId } = req.body;
        if (!installPath) {
            return res.status(400).json({
                success: false,
                error: '缺少必填参数',
                message: '安装路径为必填项'
            });
        }
        const deploymentId = `bedrock-deploy-${Date.now()}`;
        res.json({
            success: true,
            data: {
                deploymentId
            },
            message: '开始部署Minecraft基岩版服务端'
        });
        logger.info('开始部署Minecraft基岩版服务端', { installPath, platform, versionType, deploymentId });
        (async () => {
            try {
                const result = await deployBedrockServer({
                    targetDirectory: installPath,
                    platform,
                    versionType,
                    deploymentId,
                    onProgress: (message, type = 'info') => {
                        if (io && socketId) {
                            io.to(socketId).emit('more-games-deploy-log', {
                                deploymentId,
                                message,
                                type,
                                timestamp: new Date().toISOString()
                            });
                        }
                    }
                });
                if (result.success) {
                    logger.info('Minecraft基岩版服务端部署成功', {
                        installPath: result.data?.targetDirectory,
                        platform: result.data?.platform,
                        startCommand: result.data?.startCommand,
                        deploymentId: result.data?.deploymentId
                    });
                    if (io && socketId) {
                        io.to(socketId).emit('more-games-deploy-log', {
                            deploymentId,
                            message: '部署完成！',
                            type: 'success',
                            timestamp: new Date().toISOString()
                        });
                        io.to(socketId).emit('more-games-deploy-progress', {
                            deploymentId,
                            percentage: 100
                        });
                        io.to(socketId).emit('more-games-deploy-complete', {
                            deploymentId,
                            success: true,
                            data: result.data
                        });
                    }
                }
                else {
                    throw new Error(result.message || 'Minecraft基岩版部署失败');
                }
            }
            catch (error) {
                logger.error('Minecraft基岩版部署失败:', error);
                if (io && socketId) {
                    io.to(socketId).emit('more-games-deploy-error', {
                        deploymentId,
                        success: false,
                        error: error.message || 'Minecraft基岩版部署失败'
                    });
                }
            }
        })();
    }
    catch (error) {
        logger.error('启动Minecraft基岩版部署失败:', error);
        res.status(500).json({
            success: false,
            error: 'Minecraft基岩版部署失败',
            message: error.message
        });
    }
});
export default router;
