/**
 * Bot Action Executor
 * Processes bot actions and executes them in the game
 */

import { isCardPlayable } from './cardParser';

/**
 * Execute a bot action in the game
 * @param {Object} action - The bot action to execute
 * @param {Object} gameContext - Current game context
 * @returns {Object} Result of the action execution
 */
export const executeBotAction = (action, gameContext) => {
    const {
        turn,
        currentUser,
        currentColor,
        currentNumber,
        player2Deck,
        onCardPlayedHandler,
        onCardDrawnHandler,
        setUnoButtonPressed
    } = gameContext

    // Validate it's Player 2's turn and the current user is Player 2
    if (turn !== 'Player 2') {
        console.warn('❌ Bot action rejected: Not Player 2\'s turn')
        return {
            success: false,
            error: 'Not your turn',
            message: 'It\'s not Player 2\'s turn'
        }
    }

    if (currentUser !== 'Player 2') {
        console.warn('❌ Bot action rejected: Current user is not Player 2')
        return {
            success: false,
            error: 'Not Player 2',
            message: 'Current user is not Player 2'
        }
    }

    // Process the action based on type
    switch (action.action) {
        case 'play':
            return executePlayAction(action, gameContext)
        
        case 'draw':
            return executeDrawAction(gameContext)
        
        case 'uno':
            return executeUnoAction(gameContext)
        
        default:
            console.warn('❌ Unknown bot action:', action.action)
            return {
                success: false,
                error: 'Unknown action',
                message: `Unknown action type: ${action.action}`
            }
    }
}

/**
 * Execute a play card action
 */
const executePlayAction = (action, gameContext) => {
    const { card, color, callUno } = action
    const { player2Deck, onCardPlayedHandler, setUnoButtonPressed } = gameContext

    // Validate card parameter
    if (!card) {
        console.warn('❌ Bot play action rejected: No card specified')
        return {
            success: false,
            error: 'No card specified',
            message: 'Play action requires a card parameter'
        }
    }

    // Check if card is in Player 2's hand
    if (!player2Deck.includes(card)) {
        console.warn('❌ Bot play action rejected: Card not in hand:', card)
        return {
            success: false,
            error: 'Card not in hand',
            message: `Card ${card} is not in Player 2's hand`
        }
    }

    // Validate wild card has color specified
    if ((card === 'W' || card === 'D4W') && !color) {
        console.warn('❌ Bot play action rejected: Wild card without color')
        return {
            success: false,
            error: 'No color specified',
            message: 'Wild cards require a color parameter (R/G/B/Y)'
        }
    }

    // Handle UNO call if specified
    if (callUno) {
        console.log('🔥 Bot called UNO!')
        setUnoButtonPressed(true)
    }

    // Store color for wild cards in a way the game can access it
    if (color && (card === 'W' || card === 'D4W')) {
        // Set a global or context variable for the color choice
        // The onCardPlayedHandler will check this
        window.botChosenColor = color
        console.log(`🌈 Bot chose color: ${color}`)
    }

    // Execute the play
    console.log(`🎴 Bot playing card: ${card}`)
    console.log(`🎴 Current game state:`, {
        turn: gameContext.turn,
        currentUser: gameContext.currentUser,
        player2DeckLength: gameContext.player2Deck?.length,
        hasCard: gameContext.player2Deck?.includes(card)
    })
    
    // Track deck size before play to verify card was actually played
    const deckSizeBefore = gameContext.player2Deck.length
    
    onCardPlayedHandler(card)
    
    // Wait a moment for state to update
    // Note: This is a hack because onCardPlayedHandler doesn't return success/failure
    // In a real implementation, we'd need to refactor the game logic
    return new Promise((resolve) => {
        setTimeout(() => {
            const deckSizeAfter = gameContext.player2Deck.length
            const cardWasPlayed = deckSizeAfter < deckSizeBefore
            
            if (cardWasPlayed) {
                resolve({
                    success: true,
                    message: `Played card ${card}${color ? ` (chose ${color})` : ''}${callUno ? ' and called UNO' : ''}`
                })
            } else {
                console.warn('❌ Card was not actually played (deck size unchanged)')
                resolve({
                    success: false,
                    error: 'Invalid play',
                    message: `Card ${card} could not be played (invalid move)`
                })
            }
        }, 100) // Wait 100ms for state update
    })
}

/**
 * Execute a draw card action
 */
const executeDrawAction = (gameContext) => {
    const { onCardDrawnHandler } = gameContext

    console.log('📥 Bot drawing a card')
    onCardDrawnHandler()

    return {
        success: true,
        message: 'Drew a card'
    }
}

/**
 * Execute a UNO call action
 */
const executeUnoAction = (gameContext) => {
    const { setUnoButtonPressed, player2Deck } = gameContext

    if (player2Deck.length !== 2) {
        console.warn('❌ Bot UNO rejected: Player 2 doesn\'t have exactly 2 cards')
        return {
            success: false,
            error: 'Invalid UNO call',
            message: `Can only call UNO with 2 cards, currently have ${player2Deck.length}`
        }
    }

    console.log('🔥 Bot called UNO!')
    setUnoButtonPressed(true)

    return {
        success: true,
        message: 'Called UNO'
    }
}

/**
 * Validate a bot action before execution
 */
export const validateBotAction = (action, gameState) => {
    if (!action || typeof action !== 'object') {
        return { valid: false, error: 'Invalid action format' }
    }

    if (!action.action) {
        return { valid: false, error: 'Missing action type' }
    }

    // Validate specific action types
    switch (action.action) {
        case 'play':
            if (!action.card) {
                return { valid: false, error: 'Play action requires card parameter' }
            }
            if ((action.card === 'W' || action.card === 'D4W') && !action.color) {
                return { valid: false, error: 'Wild cards require color parameter' }
            }
            if (action.color && !['R', 'G', 'B', 'Y'].includes(action.color)) {
                return { valid: false, error: 'Invalid color. Must be R, G, B, or Y' }
            }
            break
        
        case 'draw':
        case 'uno':
            // No additional validation needed
            break
        
        default:
            return { valid: false, error: `Unknown action type: ${action.action}` }
    }

    return { valid: true }
}
