"""UI Domain Tools for Godot MCP.

This module provides MCP tools for UI control operations in Godot projects,
including adding UI controls, setting layout properties, and managing containers.
"""

import asyncio
from pathlib import Path

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

__all__ = [
    "ui_add_control",
    "ui_set_layout",
    "ui_add_container",
]


@mcp.tool()
def ui_add_control(
    project_path: str,
    scene_path: str,
    parent_node_path: str,
    control_type: str,
    control_name: str,
    text: str | None = None,
) -> str:
    """Add a UI control node to a scene.

    Category: UI

    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
        control_type: Type of control (Button, Label, Panel, LineEdit, TextureRect, etc.)
        control_name: Name for the new control node
        text: Text content for controls that support it (Button, Label, etc.)

    Returns:
        Success message or error description
    """
    if not all([project_path, scene_path, parent_node_path, control_type, control_name]):
        return create_error_response("All parameters except text 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,
            "parentNodePath": parent_node_path,
            "controlType": control_type,
            "controlName": control_name,
        }
        if text:
            params["text"] = text

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

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

        return f"UI control '{control_name}' ({control_type}) added to '{parent_node_path}'."

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


@mcp.tool()
def ui_set_layout(
    project_path: str,
    scene_path: str,
    node_path: str,
    anchor_preset: str | None = None,
    position: str | None = None,
    size: str | None = None,
    anchors: str | None = None,
) -> str:
    """Set layout properties for a UI control.

    Category: UI

    Args:
        project_path: Path to the Godot project directory
        scene_path: Path to the scene file (relative to project)
        node_path: Path to the control node
        anchor_preset: Preset name (FullRect, CenterTop, Center, etc.)
        position: Position as JSON array [x, y]
        size: Size as JSON array [width, height]
        anchors: Custom anchors as JSON object {"left": 0, "top": 0, "right": 1, "bottom": 1}

    Returns:
        Success message or error description
    """
    if not all([project_path, scene_path, node_path]):
        return create_error_response("project_path, scene_path, and node_path 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,
            "nodePath": node_path,
        }
        if anchor_preset:
            params["anchorPreset"] = anchor_preset
        if position:
            params["position"] = position
        if size:
            params["size"] = size
        if anchors:
            params["anchors"] = anchors

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

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

        return f"Layout properties set for '{node_path}'."

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


@mcp.tool()
def ui_add_container(
    project_path: str,
    scene_path: str,
    parent_node_path: str,
    container_type: str,
    container_name: str,
) -> str:
    """Add a UI container node to organize controls.

    Category: UI

    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
        container_type: Type of container (VBoxContainer, HBoxContainer, GridContainer, MarginContainer, etc.)
        container_name: Name for the new container node

    Returns:
        Success message or error description
    """
    if not all([project_path, scene_path, parent_node_path, container_type, container_name]):
        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,
            "parentNodePath": parent_node_path,
            "containerType": container_type,
            "containerName": container_name,
        }

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

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

        return f"UI container '{container_name}' ({container_type}) added to '{parent_node_path}'."

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