"""Timer Domain Tools for Godot MCP.

This module provides MCP tools for timer-related operations in Godot projects,
including adding timers and configuring timer properties.
"""

import asyncio
from pathlib import Path

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

__all__ = [
    "timer_add",
    "timer_configure",
]


@mcp.tool()
def timer_add(
    project_path: str,
    scene_path: str,
    parent_node_path: str,
    timer_name: str,
    wait_time: float = 1.0,
    one_shot: bool = False,
    autostart: bool = False,
) -> str:
    """Add a Timer node to a scene.

    Category: Timer

    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
        timer_name: Name for the new timer node
        wait_time: Time in seconds to wait before timeout signal (default: 1.0)
        one_shot: If true, timer stops after timeout (default: False)
        autostart: If true, timer starts automatically (default: False)

    Returns:
        Success message or error description
    """
    if not all([project_path, scene_path, parent_node_path, timer_name]):
        return create_error_response("project_path, scene_path, parent_node_path, and timer_name 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,
            "timerName": timer_name,
            "waitTime": wait_time,
            "oneShot": one_shot,
            "autostart": autostart,
        }

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

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

        return f"Timer '{timer_name}' added to '{parent_node_path}' with wait_time={wait_time}s."

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


@mcp.tool()
def timer_configure(
    project_path: str,
    scene_path: str,
    timer_path: str,
    wait_time: float | None = None,
    one_shot: bool | None = None,
    autostart: bool | None = None,
) -> str:
    """Configure properties of an existing Timer node.

    Category: Timer

    Args:
        project_path: Path to the Godot project directory
        scene_path: Path to the scene file (relative to project)
        timer_path: Path to the timer node
        wait_time: Time in seconds to wait before timeout signal
        one_shot: If true, timer stops after timeout
        autostart: If true, timer starts automatically

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

    if all(param is None for param in [wait_time, one_shot, autostart]):
        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,
            "timerPath": timer_path,
        }

        if wait_time is not None:
            params["waitTime"] = wait_time
        if one_shot is not None:
            params["oneShot"] = one_shot
        if autostart is not None:
            params["autostart"] = autostart

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

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

        return f"Timer '{timer_path}' configured successfully."

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