"""Furnish and unfurnish commands — place/remove furniture in home zones."""

from mudlib.commands import CommandDefinition, register
from mudlib.housing import save_home_zone
from mudlib.player import Player
from mudlib.targeting import find_in_inventory, find_thing_on_tile
from mudlib.zone import Zone


async def cmd_furnish(player: Player, args: str) -> None:
    """Place an item from inventory as furniture in your home zone.

    Usage:
        furnish <item>
    """
    # Validate arguments
    if not args.strip():
        await player.send("Usage: furnish <item>\r\n")
        return

    # Check that player is in their home zone
    zone = player.location
    if not isinstance(zone, Zone) or zone.name != player.home_zone:
        await player.send("You can only furnish items in your home zone.\r\n")
        return

    # Find item in inventory
    item_name = args.strip()
    thing = find_in_inventory(item_name, player)

    if thing is None:
        await player.send(f"You don't have '{item_name}'.\r\n")
        return

    # Place item at player's position
    thing.move_to(zone, x=player.x, y=player.y)

    # Save the zone
    save_home_zone(player.name, zone)

    await player.send(f"You place the {thing.name} here.\r\n")


async def cmd_unfurnish(player: Player, args: str) -> None:
    """Pick up furniture from your home zone into inventory.

    Usage:
        unfurnish <item>
    """
    # Validate arguments
    if not args.strip():
        await player.send("Usage: unfurnish <item>\r\n")
        return

    # Check that player is in their home zone
    zone = player.location
    if not isinstance(zone, Zone) or zone.name != player.home_zone:
        await player.send("You can only unfurnish items in your home zone.\r\n")
        return

    # Find furniture at player's position
    item_name = args.strip()
    thing = find_thing_on_tile(item_name, zone, player.x, player.y)

    if thing is None:
        await player.send(f"You don't see '{item_name}' here.\r\n")
        return

    # Pick up the item
    thing.move_to(player)

    # Save the zone
    save_home_zone(player.name, zone)

    await player.send(f"You pick up the {thing.name}.\r\n")


register(
    CommandDefinition(
        "furnish",
        cmd_furnish,
        help="Place an item from inventory as furniture in your home zone.",
    )
)

register(
    CommandDefinition(
        "unfurnish",
        cmd_unfurnish,
        help="Pick up furniture from your home zone into inventory.",
    )
)
