"""Terrain editing command for home zones."""

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


async def cmd_terrain(player: Player, args: str) -> None:
    """Paint terrain tiles in your home zone.

    Usage:
        terrain <tile>   — paint terrain at your current position

    Common tiles:
        .   grass
        ~   water
        ^   mountain
        T   tree
        ,   dirt
        "   tall grass
    """
    zone = player.location

    # Must be in a Zone
    if not isinstance(zone, Zone):
        await player.send("You need to be in a zone to edit terrain.\r\n")
        return

    # Must be in home zone
    if zone.name != player.home_zone:
        await player.send("You can only edit terrain in your home zone.\r\n")
        return

    # Check for args
    if not args.strip():
        await player.send(
            "Usage: terrain <tile>\r\n\r\n"
            "Common tiles: . (grass), ~ (water), ^ (mountain), "
            'T (tree), , (dirt), " (tall grass)\r\n'
        )
        return

    tile = args.strip()

    # Must be single character
    if len(tile) != 1:
        await player.send("Tile must be a single character.\r\n")
        return

    # Cannot edit border tiles
    x, y = player.x, player.y
    if x == 0 or x == zone.width - 1 or y == 0 or y == zone.height - 1:
        await player.send("You cannot edit the border walls.\r\n")
        return

    # Paint the tile
    zone.terrain[y][x] = tile

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

    await player.send(f"You paint the ground beneath you as '{tile}'.\r\n")


register(
    CommandDefinition(
        "terrain",
        cmd_terrain,
        help="Paint terrain tiles in your home zone.",
    )
)
