"""Edit command for entering the text editor."""

from pathlib import Path

from mudlib.commands import CommandDefinition, register
from mudlib.editor import Editor
from mudlib.player import Player


async def cmd_edit(player: Player, args: str) -> None:
    """Enter the text editor.

    Args:
        player: The player entering the editor
        args: Optional argument - combat move name to edit
    """
    args = args.strip()

    # Default: blank editor
    initial_content = ""
    content_type = "text"
    save_callback_fn = _make_default_save_callback(player)
    toml_path: Path | None = None

    # If args provided, try to load combat move TOML
    if args:
        from mudlib.combat.commands import combat_content_dir, combat_moves

        if combat_content_dir is None:
            await player.send("Combat content not loaded.\r\n")
            return

        # Look up the move - could be by name or alias
        move = combat_moves.get(args)

        # If not found, try to find by command name (for variant bases)
        if move is None:
            for m in combat_moves.values():
                if m.command == args:
                    move = m
                    break

        if move is None:
            await player.send(f"Unknown content: {args}\r\n")
            return

        # Get the base command name to find the TOML file
        toml_filename = f"{move.command}.toml"
        toml_path = combat_content_dir / toml_filename

        if not toml_path.exists():
            await player.send(f"TOML file not found: {toml_filename}\r\n")
            return

        # Read the file content
        initial_content = toml_path.read_text()
        content_type = "toml"
        save_callback_fn = _make_toml_save_callback(player, toml_path)

    player.editor = Editor(
        save_callback=save_callback_fn,
        content_type=content_type,
        color_depth=player.color_depth or "16",
        initial_content=initial_content,
    )
    player.mode_stack.append("editor")
    await player.send("Entering editor. Type :h for help.\r\n")


def _make_default_save_callback(player: Player):
    """Create default save callback for blank editor."""

    async def save_callback(content: str) -> None:
        await player.send("Content saved.\r\n")

    return save_callback


def _make_toml_save_callback(player: Player, toml_path: Path):
    """Create save callback for TOML file editing."""

    async def save_callback(content: str) -> None:
        toml_path.write_text(content)
        await player.send(f"Saved {toml_path.name}\r\n")

    return save_callback


# Register the edit command
register(CommandDefinition("edit", cmd_edit, mode="normal"))
