import { world, system } from '@minecraft/server';
import { processBlocksAbove, debugLog, initializeSystem } from './utils.js';

/**
 * Handle player break block events
 * @param {PlayerBreakBlockBeforeEvent} event - The break block event
 */
function handlePlayerBreakBlock(event) {
    try {
        const { block, dimension } = event;
        const position = block.location;
        
        debugLog(`Player broke block ${block.typeId} at ${position.x}, ${position.y}, ${position.z}`);
        
        // Process blocks above this position on the next tick to ensure the block is actually broken
        system.runTimeout(() => {
            processBlocksAbove(dimension, position);
        }, 1);
        
    } catch (error) {
        debugLog(`Error in handlePlayerBreakBlock: ${error.message}`);
    }
}

/**
 * Handle explosion events
 * @param {ExplosionBeforeEvent} event - The explosion event
 */
function handleExplosion(event) {
    try {
        const { dimension } = event;
        const impactedBlocks = event.getImpactedBlocks();
        
        debugLog(`Explosion detected, checking ${impactedBlocks.length} impacted blocks`);
        
        // Process each impacted block position on the next tick
        system.runTimeout(() => {
            for (const blockLocation of impactedBlocks) {
                processBlocksAbove(dimension, blockLocation);
            }
        }, 1);
        
    } catch (error) {
        debugLog(`Error in handleExplosion: ${error.message}`);
    }
}

/**
 * Handle block explosion events (alternative explosion handling)
 * @param {BlockExplodeAfterEvent} event - The block explode event
 */
function handleBlockExplosion(event) {
    try {
        const { dimension, explodedBlockPermutation } = event;
        const destroyedBlocks = event.getDestroyedBlocks();
        
        debugLog(`Block explosion detected, checking ${destroyedBlocks.length} destroyed blocks`);
        
        // Process each destroyed block position
        system.runTimeout(() => {
            for (const blockLocation of destroyedBlocks) {
                processBlocksAbove(dimension, blockLocation);
            }
        }, 1);
        
    } catch (error) {
        debugLog(`Error in handleBlockExplosion: ${error.message}`);
    }
}

/**
 * Initialize event listeners
 */
function setupEventListeners() {
    try {
        // Listen for player break block events
        world.beforeEvents.playerBreakBlock.subscribe(handlePlayerBreakBlock);
        debugLog("Player break block event listener registered");
        
        // Listen for explosion events
        world.beforeEvents.explosion.subscribe(handleExplosion);
        debugLog("Explosion event listener registered");
        
        // Listen for block explosion events (if available)
        try {
            world.afterEvents.blockExplode.subscribe(handleBlockExplosion);
            debugLog("Block explosion event listener registered");
        } catch (blockExplodeError) {
            debugLog("Block explosion events not available in this version");
        }
        
    } catch (error) {
        debugLog(`Error setting up event listeners: ${error.message}`);
    }
}

/**
 * Main initialization function
 */
function main() {
    try {
        debugLog("Starting break-below system initialization");
        
        // Initialize the system
        initializeSystem();
        
        // Set up event listeners
        setupEventListeners();
        
        debugLog("Break-below system fully initialized and ready");
        
    } catch (error) {
        debugLog(`Critical error in main initialization: ${error.message}`);
    }
}

// Initialize the system when the script loads
system.runTimeout(() => {
    main();
}, 20); // Small delay to ensure world is fully loaded

// Export main function for potential external use
export { main };
