"""Autoload Domain Tools for Godot MCP.

This module provides MCP tools for managing autoload singletons in Godot projects.
"""

import asyncio
from pathlib import Path

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

__all__ = [
    "autoload_add",
    "autoload_remove",
    "autoload_list",
]


@mcp.tool()
def autoload_add(
    project_path: str,
    name: str,
    script_path: str,
) -> str:
    """Add an autoload singleton to the project.

    Category: Autoload

    Args:
        project_path: Path to the Godot project directory
        name: Name of the autoload (will be accessible as global)
        script_path: Path to the script file (relative to project)

    Returns:
        Success message or error description
    """
    if not all([project_path, name, script_path]):
        return create_error_response("All parameters are required")

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

    try:
        project_file = Path(project_path) / "project.godot"
        if not project_file.exists():
            return create_error_response(f"Not a valid Godot project: {project_path}")

        script_full_path = Path(project_path) / script_path
        if not script_full_path.exists():
            return create_error_response(f"Script file does not exist: {script_path}")

        params = {
            "name": name,
            "scriptPath": script_path,
        }

        stdout, stderr = asyncio.run(
            godot_server.execute_operation("add_autoload", params, project_path)
        )

        if stderr and ("Failed to" in stderr or "[ERROR]" in stderr):
            return create_error_response(f"Failed to add autoload: {stderr}")

        return f"Autoload '{name}' added for script '{script_path}'."

    except Exception as error:
        return create_error_response(f"Failed to add autoload: {error}")


@mcp.tool()
def autoload_remove(
    project_path: str,
    name: str,
) -> str:
    """Remove an autoload singleton from the project.

    Category: Autoload

    Args:
        project_path: Path to the Godot project directory
        name: Name of the autoload to remove

    Returns:
        Success message or error description
    """
    if not all([project_path, name]):
        return create_error_response("Both project_path and name are required")

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

    try:
        project_file = Path(project_path) / "project.godot"
        if not project_file.exists():
            return create_error_response(f"Not a valid Godot project: {project_path}")

        params = {
            "name": name,
        }

        stdout, stderr = asyncio.run(
            godot_server.execute_operation("remove_autoload", params, project_path)
        )

        if stderr and ("Failed to" in stderr or "[ERROR]" in stderr):
            return create_error_response(f"Failed to remove autoload: {stderr}")

        return f"Autoload '{name}' removed."

    except Exception as error:
        return create_error_response(f"Failed to remove autoload: {error}")


@mcp.tool()
def autoload_list(
    project_path: str,
) -> str:
    """List all autoload singletons in the project.

    Category: Autoload

    Args:
        project_path: Path to the Godot project directory

    Returns:
        JSON string containing list of autoloads or error description
    """
    if not project_path:
        return create_error_response("project_path is required")

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

    try:
        project_file = Path(project_path) / "project.godot"
        if not project_file.exists():
            return create_error_response(f"Not a valid Godot project: {project_path}")

        params = {}

        stdout, stderr = asyncio.run(
            godot_server.execute_operation("list_autoloads", params, project_path)
        )

        if stderr and ("Failed to" in stderr or "[ERROR]" in stderr):
            return create_error_response(f"Failed to list autoloads: {stderr}")

        json_output = extract_json_from_output(stdout)
        if json_output:
            return json_output

        return stdout

    except Exception as error:
        return create_error_response(f"Failed to list autoloads: {error}")
