"""Input Domain Tools for Godot MCP.

This module provides MCP tools for managing input actions and key bindings
in Godot projects, including setting up input actions and listing existing
input mappings.
"""

import asyncio

from pathlib import Path

from godot_mcp.core import (
    mcp,
    godot_server,
    create_error_response,
    validate_path,
    extract_json_from_output,
)


__all__ = [
    "input_setup_action",
    "input_list_actions",
]


@mcp.tool()
def input_setup_action(
    project_path: str,
    action_name: str,
    keys: list[str],
) -> str:
    """Set up an input action with key bindings in the project's input map.

    Category: Input

    Args:
        project_path: Path to the Godot project directory
        action_name: Name of the input action (e.g., "jump", "move_left")
        keys: List of key strings to bind (e.g., ["Space", "W", "Ctrl+S"])
              Supported keys: A-Z, 0-9, F1-F12, Space, Enter, Tab, Escape,
              Arrow keys (Up, Down, Left, Right), and modifiers (Ctrl+, Alt+, Shift+, Meta+)
    """
    if not project_path or not action_name:
        return create_error_response("Project path and action name are required")

    if not validate_path(project_path):
        return create_error_response("Invalid project path")

    try:
        # Check if the project directory exists and contains a project.godot file
        project_file = Path(project_path) / "project.godot"
        if not project_file.exists():
            return create_error_response(
                f"Not a valid Godot project: {project_path}",
                ["Ensure the path points to a directory containing a project.godot file"],
            )

        # Prepare parameters for the operation
        params = {
            "actionName": action_name,
            "keys": keys if keys else [],
        }

        # Execute the operation
        stdout, stderr = asyncio.run(
            godot_server.execute_operation("setup_input_map", params, project_path)
        )

        if stderr and "Failed to" in stderr:
            return create_error_response(
                f"Failed to setup input map: {stderr}",
                [
                    "Check if the key names are valid",
                    "Ensure you have write permissions",
                ],
            )

        return f"Input action '{action_name}' set up successfully with keys: {keys}"
    except Exception as error:
        return create_error_response(
            f"Failed to setup input map: {error}",
            [
                "Ensure Godot is installed correctly",
                "Verify the project path is accessible",
            ],
        )


@mcp.tool()
def input_list_actions(project_path: str) -> str:
    """List all input actions defined in the project's input map.

    Category: Input

    Args:
        project_path: Path to the Godot project directory

    Returns:
        JSON containing all input actions with their key bindings
    """
    if not project_path:
        return create_error_response("Project path is required")

    if not validate_path(project_path):
        return create_error_response("Invalid project path")

    try:
        # Check if the project directory exists and contains a project.godot file
        project_file = Path(project_path) / "project.godot"
        if not project_file.exists():
            return create_error_response(
                f"Not a valid Godot project: {project_path}",
                ["Ensure the path points to a directory containing a project.godot file"],
            )

        # Prepare parameters for the operation
        params = {}

        # Execute the operation
        stdout, stderr = asyncio.run(
            godot_server.execute_operation("list_input_actions", params, project_path)
        )

        if stderr and "Failed to" in stderr:
            return create_error_response(
                f"Failed to list input actions: {stderr}",
                ["Ensure the project is valid"],
            )

        # Extract and return the JSON output from the GDScript
        return extract_json_from_output(stdout)
    except Exception as error:
        return create_error_response(
            f"Failed to list input actions: {error}",
            [
                "Ensure Godot is installed correctly",
                "Verify the project path is accessible",
            ],
        )
