const { PythonShell } = require('python-shell');
const path = require('path');
const fs = require('fs');

// Function to process the tileset image and update the TSX file
function processTilesetImage(imagePath, tsxPath, sensitivity = 100, output = null) {
    return new Promise((resolve, reject) => {
        console.log(`Processing tileset image: ${imagePath}`);

        const options = {
            mode: 'text',
            pythonPath: 'python',
            pythonOptions: ['-u'], // unbuffered output
            scriptPath: __dirname,
            args: [imagePath, tsxPath, sensitivity.toString()]
        };

        PythonShell.run('collision_detector.py', options, (err, results) => {
            if (err) {
                console.error('Error processing tileset image:', err);
                reject(err);
            } else {
                console.log('Tileset image processed successfully');
                resolve(results);
            }
        });
    });
}

// Function to create the base TMX map
function tileBaseMapForGeneration(mapType, width, height, perTileSize, outputMapPath) {
    return new Promise((resolve, reject) => {
        console.log(`Creating base map with type: ${mapType}, width: ${width}, height: ${height}, tileSize: ${perTileSize.x}x${perTileSize.y}`);

        // Assuming we have a Python script to create the base map
        const options = {
            mode: 'text',
            pythonPath: 'python',
            pythonOptions: ['-u'],
            scriptPath: __dirname,
            args: [
                '--map_type', mapType,
                '--width', width.toString(),
                '--height', height.toString(),
                '--tile_width', perTileSize.x.toString(),
                '--tile_height', perTileSize.y.toString(),
                '--output', outputMapPath
            ]
        };

        PythonShell.run('create_base_map.py', options, (err, results) => {
            if (err) {
                console.error('Error creating base map:', err);
                reject(err);
            } else {
                console.log('Base map created successfully');
                resolve(results);
            }
        });
    });
}

// Map generation function
function generateMap(mapPath, difficulty = 0.5) {
    return new Promise((resolve, reject) => {
        console.log(`Starting map generation with path: ${mapPath} and difficulty: ${difficulty}`);
        
        const options = {
            mode: 'text',
            pythonPath: 'python', // Python interpreter path
            pythonOptions: ['-u'], // unbuffered output
            scriptPath: __dirname, // Script directory
            args: [
                '--map', mapPath,
                '--difficulty', difficulty.toString()
            ]
        };

        PythonShell.run('ai_controller.py', options, (err, results) => {
            if (err) {
                console.error('Error running AI controller:', err);
                reject(err);
            } else {
                console.log('Python script executed successfully');
                if (results && results.length > 0) {
                    console.log('Map generation completed:');
                    results.forEach(result => console.log(result));
                    resolve(results);
                } else {
                    console.error('No results returned or unexpected output.');
                    reject(new Error('No results returned.'));
                }
            }
        });
    });
}

// Main function
async function main() {
    try {
        // Paths to your tileset image and TSX file
        const imagePath = path.join(__dirname, 'maps', 'boş', 'fabrika (2).png');
        const tsxPath = path.join(__dirname, 'maps', 'boş', 'tsx', 'fabrika.tmx');

        // Process the tileset image to add colliders
        await processTilesetImage(imagePath, tsxPath, 100);

        // Map parameters
        const mapType = 'platform'; // or 'top-down', 'isometric'
        const width = 100; // example width
        const height = 50; // example height
        const perTileSize = { x: 32, y: 32 }; // example tile size

        // Output map path
        const outputMapPath = path.join(__dirname, 'output', 'newMaps', 'level1.tmx');

        // Create the base map
        await tileBaseMapForGeneration(mapType, width, height, perTileSize, outputMapPath);

        // Check if the base map was created
        if (!fs.existsSync(outputMapPath)) {
            console.error(`Base map file does not exist: ${outputMapPath}`);
            return;
        }

        console.log('Starting map generation...');
        // Generate the map using the base map
        await generateMap(outputMapPath, 0.7);
        console.log('Map generation completed successfully');
    } catch (error) {
        console.error('Map generation failed:', error);
        process.exit(1);
    }
}

// Run the main function if this file is executed directly
if (require.main === module) {
    main();
}

output da ekler misin