"""CanvasLayer Domain Tools for Godot MCP.

This module provides MCP tools for canvas layer operations in Godot projects,
used for managing UI layer ordering and positioning.
"""

import asyncio
from pathlib import Path

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

__all__ = [
    "canvas_layer_add",
    "canvas_layer_set_order",
    "canvas_layer_configure",
]


@mcp.tool()
def canvas_layer_add(
    project_path: str,
    scene_path: str,
    parent_node_path: str,
    layer_name: str,
    layer_order: int = 0,
) -> str:
    """Add a CanvasLayer node to organize UI elements by depth.

    Category: CanvasLayer

    Args:
        project_path: Path to the Godot project directory
        scene_path: Path to the scene file (relative to project)
        parent_node_path: Path to the parent node
        layer_name: Name for the new canvas layer
        layer_order: Layer rendering order (higher values render on top, default: 0)

    Returns:
        Success message or error description
    """
    if not all([project_path, scene_path, parent_node_path, layer_name]):
        return create_error_response("All parameters except layer_order are required")

    if not validate_path(project_path) or not validate_path(scene_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}")

        scene_full_path = Path(project_path) / scene_path
        if not scene_full_path.exists():
            return create_error_response(f"Scene file does not exist: {scene_path}")

        params = {
            "scenePath": scene_path,
            "parentNodePath": parent_node_path,
            "layerName": layer_name,
            "layerOrder": layer_order,
        }

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

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

        return f"CanvasLayer '{layer_name}' added with order {layer_order}."

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


@mcp.tool()
def canvas_layer_set_order(
    project_path: str,
    scene_path: str,
    layer_path: str,
    layer_order: int,
) -> str:
    """Set the rendering order of a CanvasLayer.

    Category: CanvasLayer

    Args:
        project_path: Path to the Godot project directory
        scene_path: Path to the scene file (relative to project)
        layer_path: Path to the canvas layer node
        layer_order: Layer rendering order (higher values render on top)

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

    if not validate_path(project_path) or not validate_path(scene_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 = {
            "scenePath": scene_path,
            "layerPath": layer_path,
            "layerOrder": layer_order,
        }

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

        if stderr and ("Failed to" in stderr or "[ERROR]" in stderr):
            return create_error_response(f"Failed to set canvas layer order: {stderr}")

        return f"CanvasLayer '{layer_path}' order set to {layer_order}."

    except Exception as error:
        return create_error_response(f"Failed to set canvas layer order: {error}")


@mcp.tool()
def canvas_layer_configure(
    project_path: str,
    scene_path: str,
    layer_path: str,
    offset: str | None = None,
    rotation: float | None = None,
    scale: str | None = None,
    follow_viewport: bool | None = None,
) -> str:
    """Configure properties of a CanvasLayer.

    Category: CanvasLayer

    Args:
        project_path: Path to the Godot project directory
        scene_path: Path to the scene file (relative to project)
        layer_path: Path to the canvas layer node
        offset: Offset as JSON array [x, y]
        rotation: Rotation in radians
        scale: Scale as JSON array [x, y]
        follow_viewport: Whether to follow the viewport

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

    if all(param is None for param in [offset, rotation, scale, follow_viewport]):
        return create_error_response("At least one configuration parameter must be specified")

    if not validate_path(project_path) or not validate_path(scene_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 = {
            "scenePath": scene_path,
            "layerPath": layer_path,
        }

        if offset:
            params["offset"] = offset
        if rotation is not None:
            params["rotation"] = rotation
        if scale:
            params["scale"] = scale
        if follow_viewport is not None:
            params["followViewport"] = follow_viewport

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

        if stderr and ("Failed to" in stderr or "[ERROR]" in stderr):
            return create_error_response(f"Failed to configure canvas layer: {stderr}")

        return f"CanvasLayer '{layer_path}' configured successfully."

    except Exception as error:
        return create_error_response(f"Failed to configure canvas layer: {error}")
