"""
Pickup and item collection handlers.
"""
import logging
from . import keyboards, logic
from .api_client import api_client
from data.world_loader import game_world
from data.items import ITEMS

logger = logging.getLogger(__name__)


async def handle_pickup_menu(query, user_id: int, player: dict, data: list):
    """Show pickup options for a dropped item."""
    dropped_item_id = int(data[1])
    item_to_pickup = await api_client.get_dropped_item(dropped_item_id)
    
    if not item_to_pickup:
        await query.answer("Someone already picked that up!", show_alert=False)
        location_id = player['location_id']
        location = game_world.get_location(location_id)
        dropped_items = await api_client.get_dropped_items_in_location(location_id)
        wandering_enemies = await api_client.get_wandering_enemies_in_location(location_id)
        keyboard = await keyboards.inspect_keyboard(location_id, dropped_items, wandering_enemies)
        image_path = location.image_path if location else None
        
        from .handlers import send_or_edit_with_image
        await send_or_edit_with_image(
            query,
            text="You scan the area. You notice...",
            reply_markup=keyboard,
            image_path=image_path
        )
        return
    
    item_def = ITEMS.get(item_to_pickup['item_id'], {})
    emoji = item_def.get('emoji', '❔')
    text = f"{emoji} <b>{item_def.get('name', 'Unknown')}</b>\n\n"
    text += f"Available: {item_to_pickup['quantity']}\n"
    text += f"Weight: {item_def.get('weight', 0)} kg each\n"
    text += f"Volume: {item_def.get('volume', 0)} vol each\n\n"
    text += "How many do you want to pick up?"
    
    await query.answer()
    keyboard = keyboards.pickup_options_keyboard(
        dropped_item_id,
        item_def.get('name', 'Unknown'),
        item_to_pickup['quantity']
    )
    
    location = game_world.get_location(player['location_id'])
    image_path = location.image_path if location else None
    
    from .handlers import send_or_edit_with_image
    await send_or_edit_with_image(
        query,
        text=text,
        reply_markup=keyboard,
        image_path=image_path
    )


async def handle_pickup(query, user_id: int, player: dict, data: list):
    """Pick up a dropped item from the world."""
    dropped_item_id = int(data[1])
    pickup_amount_str = data[2] if len(data) > 2 else "all"
    
    item_to_pickup = await api_client.get_dropped_item(dropped_item_id)
    if not item_to_pickup:
        await query.answer("Someone already picked that up!", show_alert=False)
        location_id = player['location_id']
        location = game_world.get_location(location_id)
        dropped_items = await api_client.get_dropped_items_in_location(location_id)
        wandering_enemies = await api_client.get_wandering_enemies_in_location(location_id)
        keyboard = await keyboards.inspect_keyboard(location_id, dropped_items, wandering_enemies)
        image_path = location.image_path if location else None
        
        from .handlers import send_or_edit_with_image
        await send_or_edit_with_image(
            query,
            text="You scan the area. You notice...",
            reply_markup=keyboard,
            image_path=image_path
        )
        return
    
    # Determine how much to pick up
    if pickup_amount_str == "all":
        pickup_amount = item_to_pickup['quantity']
    else:
        pickup_amount = min(int(pickup_amount_str), item_to_pickup['quantity'])
    
    # Check inventory capacity
    can_add, reason = await logic.can_add_item_to_inventory(
        user_id, item_to_pickup['item_id'], pickup_amount
    )
    
    if not can_add:
        await query.answer(reason, show_alert=True)
        return
    
    # Add to inventory
    await api_client.add_item_to_inventory(user_id, item_to_pickup['item_id'], pickup_amount)
    
    # Update or remove dropped item
    remaining = item_to_pickup['quantity'] - pickup_amount
    item_def = ITEMS.get(item_to_pickup['item_id'], {})
    
    if remaining > 0:
        await api_client.update_dropped_item(dropped_item_id, remaining)
        await query.answer(
            f"Picked up {pickup_amount}x {item_def.get('name', 'item')}. {remaining} remaining.",
            show_alert=False
        )
    else:
        await api_client.remove_dropped_item(dropped_item_id)
        await query.answer(
            f"Picked up {pickup_amount}x {item_def.get('name', 'item')}.",
            show_alert=False
        )
    
    # Return to inspect area
    location_id = player['location_id']
    location = game_world.get_location(location_id)
    dropped_items = await api_client.get_dropped_items_in_location(location_id)
    wandering_enemies = await api_client.get_wandering_enemies_in_location(location_id)
    keyboard = await keyboards.inspect_keyboard(location_id, dropped_items, wandering_enemies)
    image_path = location.image_path if location else None
    
    from .handlers import send_or_edit_with_image
    await send_or_edit_with_image(
        query,
        text="You scan the area. You notice...",
        reply_markup=keyboard,
        image_path=image_path
    )
