import { spawn } from 'child_process';
import { promisify } from 'util';
import { exec } from 'child_process';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import logger from './logger.js';
const execAsync = promisify(exec);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PYTHON_SCRIPT_PATH = path.join(__dirname, '..', 'Python', 'game_config_manager.py');
let pythonDepsInstalled = false;
let pythonEnvironmentFailed = false;
let pythonFailureCount = 0;
const MAX_PYTHON_RETRY_COUNT = 3;
export class PythonManager {
    static getPythonCommand() {
        const platform = os.platform();
        if (platform === 'win32') {
            return 'python';
        }
        else {
            return 'python3';
        }
    }
    static checkPythonCommand(command) {
        return new Promise((resolve) => {
            const testProcess = spawn(command, ['--version'], { stdio: 'ignore' });
            testProcess.on('close', (code) => {
                resolve(code === 0);
            });
            testProcess.on('error', () => {
                resolve(false);
            });
        });
    }
    static async getAvailablePythonCommand() {
        const platform = os.platform();
        if (platform === 'win32') {
            const commands = ['python', 'python3'];
            for (const cmd of commands) {
                if (await this.checkPythonCommand(cmd)) {
                    logger.info(`Windows平台使用Python命令: ${cmd}`);
                    return cmd;
                }
            }
        }
        else {
            const commands = ['python3', 'python'];
            for (const cmd of commands) {
                if (await this.checkPythonCommand(cmd)) {
                    logger.info(`${platform}平台使用Python命令: ${cmd}`);
                    return cmd;
                }
            }
        }
        throw new Error('未找到可用的Python命令');
    }
    static callPythonScript(method, args = []) {
        return new Promise(async (resolve, reject) => {
            try {
                const pythonCommand = await this.getAvailablePythonCommand();
                logger.info(`使用Python命令: ${pythonCommand}`);
                const pythonArgs = [PYTHON_SCRIPT_PATH, method, ...args.map(arg => JSON.stringify(arg))];
                const pythonProcess = spawn(pythonCommand, pythonArgs, {
                    stdio: ['pipe', 'pipe', 'pipe'],
                    env: {
                        ...process.env,
                        PYTHONIOENCODING: 'utf-8'
                    }
                });
                let stdout = '';
                let stderr = '';
                pythonProcess.stdout.on('data', (data) => {
                    stdout += data.toString('utf8');
                });
                pythonProcess.stderr.on('data', (data) => {
                    stderr += data.toString('utf8');
                });
                pythonProcess.on('close', (code) => {
                    if (stderr) {
                        logger.info(`Python脚本日志: ${stderr}`);
                    }
                    if (code === 0) {
                        try {
                            const result = JSON.parse(stdout);
                            resolve(result);
                        }
                        catch (error) {
                            logger.error(`JSON解析失败: ${error}, stdout: ${stdout}`);
                            reject(new Error(`JSON解析失败: ${error}`));
                        }
                    }
                    else {
                        logger.error(`Python脚本执行失败，退出码: ${code}, stderr: ${stderr}, stdout: ${stdout}`);
                        reject(new Error(`Python脚本执行失败: ${stderr}`));
                    }
                });
                pythonProcess.on('error', (error) => {
                    logger.error(`Python进程启动失败: ${error.message}`);
                    reject(new Error(`启动Python进程失败: ${error.message}`));
                });
            }
            catch (error) {
                reject(error);
            }
        });
    }
    static async checkPythonEnvironment() {
        try {
            const platform = os.platform();
            logger.info(`检测Python环境，平台: ${platform}`);
            const pythonCommand = await this.getAvailablePythonCommand();
            logger.info(`检测Python环境，平台: ${platform}，使用命令: ${pythonCommand}`);
            const { stdout } = await execAsync(`${pythonCommand} --version`);
            const version = stdout.trim();
            logger.info(`Python环境检测成功: ${version}`);
            return {
                available: true,
                version: version,
                command: pythonCommand,
                platform: platform
            };
        }
        catch (error) {
            logger.error('Python环境检测异常:', error);
            return {
                available: false,
                error: `未检测到Python环境: ${error.message}`,
                platform: os.platform()
            };
        }
    }
    static async getAvailableConfigs() {
        return await this.callPythonScript('get_available_configs');
    }
    static async getConfigSchema(configId) {
        return await this.callPythonScript('get_config_schema', [configId]);
    }
    static async readGameConfig(workingDirectory, schema, parser = 'configobj') {
        return await this.callPythonScript('read_game_config', [
            workingDirectory,
            schema,
            parser
        ]);
    }
    static async saveGameConfig(workingDirectory, schema, configData, parser = 'configobj') {
        return await this.callPythonScript('save_game_config', [
            workingDirectory,
            schema,
            configData,
            parser
        ]);
    }
}
export default PythonManager;
