// Inventory Validation System for Structure Items
// Continuously monitors and removes structure-exclusive blocks from player inventories

import { world, system } from '@minecraft/server';
import { isExclusiveStructureBlock } from './config.js';
import { debug } from './utils.js';

// Configuration
const INVENTORY_CHECK_INTERVAL = 20; // Check every 2 seconds (40 ticks at 20 TPS)
const ALLOW_CREATIVE_MODE = false; // Allow creative mode players to keep structure blocks
const ALLOW_OP_PLAYERS = false; // Allow operator players to keep structure blocks

let isInventoryValidatorRunning = false;

/**
 * Initialize the inventory validation system
 */
export function initializeInventoryValidator() {
  if (isInventoryValidatorRunning) {
    debug('warn', 'Inventory validator already running');
    return;
  }
  
  // Start the periodic inventory check
  system.runInterval(() => {
    validateAllPlayerInventories();
  }, INVENTORY_CHECK_INTERVAL);
  
  isInventoryValidatorRunning = true;
  debug('info', `Inventory validator started (checking every ${INVENTORY_CHECK_INTERVAL} ticks)`);
}

/**
 * Stop the inventory validation system
 */
export function stopInventoryValidator() {
  isInventoryValidatorRunning = false;
  debug('info', 'Inventory validator stopped');
}

/**
 * Check all online players' inventories for structure-exclusive blocks
 */
function validateAllPlayerInventories() {
  const players = world.getAllPlayers();
  
  if (players.length === 0) {
    return; // No players online
  }
  
  let totalPlayersChecked = 0;
  let totalBlocksRemoved = 0;
  
  for (const player of players) {
    try {
      const removedCount = validatePlayerInventory(player);
      totalBlocksRemoved += removedCount;
      totalPlayersChecked++;
    } catch (error) {
      debug('error', `Failed to validate inventory for player ${player.name}: ${error.message}`);
    }
  }
  
  // Log summary only if blocks were removed
  if (totalBlocksRemoved > 0) {
    debug('info', `Inventory validation complete: ${totalBlocksRemoved} blocks removed from ${totalPlayersChecked} players`);
  }
}

/**
 * Validate a single player's inventory and remove structure-exclusive blocks
 * @param {Player} player - The player to validate
 * @returns {number} Number of blocks removed
 */
function validatePlayerInventory(player) {
  // Check if player should be exempt from validation
  if (shouldExemptPlayer(player)) {
    return 0;
  }
  
  const inventory = player.getComponent('inventory');
  if (!inventory) {
    debug('warn', `Could not access inventory for player ${player.name}`);
    return 0;
  }
  
  const container = inventory.container;
  let blocksRemoved = 0;
  
  // Check all inventory slots
  for (let slot = 0; slot < container.size; slot++) {
    try {
      const item = container.getItem(slot);
      
      if (item && isExclusiveStructureBlock(item.typeId)) {
        // Remove the structure block
        container.setItem(slot, undefined);
        blocksRemoved += item.amount;
        
        debug('info', `Removed ${item.amount}x ${item.typeId} from ${player.name}'s inventory (slot ${slot})`);
        
        // Notify player
        player.onScreenDisplay.setActionBar(`§cRemoved illegal structure block: ${item.typeId}`);
      }
    } catch (error) {
      debug('error', `Error checking inventory slot ${slot} for ${player.name}: ${error.message}`);
    }
  }
  
  return blocksRemoved;
}

/**
 * Check if a player should be exempt from inventory validation
 * @param {Player} player - The player to check
 * @returns {boolean} True if player should be exempt
 */
function shouldExemptPlayer(player) {
  // Exempt creative mode players (if configured)
  if (ALLOW_CREATIVE_MODE && player.getGameMode() === 'creative') {
    return true;
  }
  
  // Exempt operator players (if configured)
  if (ALLOW_OP_PLAYERS && player.isOp()) {
    return true;
  }
  
  // Exempt players with special permission tag
  if (player.hasTag('structure_admin')) {
    return true;
  }
  
  return false;
}

/**
 * Manually validate a specific player's inventory (for immediate checks)
 * @param {Player} player - The player to validate
 * @returns {Object} Validation result
 */
export function validatePlayerInventoryNow(player) {
  try {
    const removedCount = validatePlayerInventory(player);
    return {
      success: true,
      blocksRemoved: removedCount,
      message: removedCount > 0 ? 
        `Removed ${removedCount} illegal structure blocks` : 
        'No illegal blocks found'
    };
  } catch (error) {
    return {
      success: false,
      blocksRemoved: 0,
      message: `Error validating inventory: ${error.message}`
    };
  }
}

/**
 * Force validate all players' inventories immediately
 * @returns {Object} Validation summary
 */
export function validateAllInventoriesNow() {
  debug('info', 'Force validating all player inventories');
  
  const players = world.getAllPlayers();
  let totalPlayersChecked = 0;
  let totalBlocksRemoved = 0;
  let errors = [];
  
  for (const player of players) {
    try {
      const removedCount = validatePlayerInventory(player);
      totalBlocksRemoved += removedCount;
      totalPlayersChecked++;
    } catch (error) {
      errors.push(`${player.name}: ${error.message}`);
    }
  }
  
  const result = {
    playersChecked: totalPlayersChecked,
    blocksRemoved: totalBlocksRemoved,
    errors: errors
  };
  
  debug('info', `Force validation complete: ${JSON.stringify(result)}`);
  return result;
}

/**
 * Get current inventory validator status
 * @returns {Object} Status information
 */
export function getInventoryValidatorStatus() {
  return {
    isRunning: isInventoryValidatorRunning,
    checkInterval: INVENTORY_CHECK_INTERVAL,
    allowCreativeMode: ALLOW_CREATIVE_MODE,
    allowOpPlayers: ALLOW_OP_PLAYERS,
    onlinePlayerCount: world.getAllPlayers().length
  };
}

/**
 * Update inventory validation configuration
 * @param {Object} config - Configuration options
 */
export function updateInventoryValidatorConfig(config) {
  if (typeof config.allowCreativeMode === 'boolean') {
    ALLOW_CREATIVE_MODE = config.allowCreativeMode;
    debug('info', `Updated allowCreativeMode: ${ALLOW_CREATIVE_MODE}`);
  }
  
  if (typeof config.allowOpPlayers === 'boolean') {
    ALLOW_OP_PLAYERS = config.allowOpPlayers;
    debug('info', `Updated allowOpPlayers: ${ALLOW_OP_PLAYERS}`);
  }
}

/**
 * Check if a specific item type is allowed in inventories
 * @param {string} itemTypeId - The item type to check
 * @param {Player} player - The player context
 * @returns {boolean} True if item is allowed
 */
export function isItemAllowedInInventory(itemTypeId, player) {
  if (!isExclusiveStructureBlock(itemTypeId)) {
    return true; // Not a structure block, allow it
  }
  
  return shouldExemptPlayer(player);
} 