"""Action executor — dispatches desktop actions to the appropriate handler."""

import time
import json


def execute_actions(actions):
    """Execute a list of desktop actions sequentially. Returns combined results."""
    results = []

    for action in actions:
        action_type = action.get("type", "unknown")
        action_id = action.get("id", "?")

        try:
            result = _dispatch(action_type, action)
            result["action_id"] = action_id
            result["action_type"] = action_type
        except Exception as e:
            result = {
                "action_id": action_id,
                "action_type": action_type,
                "success": False,
                "error": str(e),
            }

        results.append(result)

        # If an action fails, continue with remaining actions
        # (the AI can decide what to do based on results)

    return results


def _dispatch(action_type, action):
    """Route an action to its handler."""

    # Screenshot
    if action_type == "screenshot":
        from .actions.screenshot import take_screenshot
        return take_screenshot()

    # Mouse
    elif action_type == "mouse_click":
        from .actions.mouse import mouse_click
        return mouse_click(
            action.get("x", 0), action.get("y", 0),
            action.get("button", "left"), action.get("clicks", 1),
        )
    elif action_type == "mouse_move":
        from .actions.mouse import mouse_move
        return mouse_move(action.get("x", 0), action.get("y", 0))
    elif action_type == "mouse_drag":
        from .actions.mouse import mouse_drag
        return mouse_drag(
            action.get("from_x", 0), action.get("from_y", 0),
            action.get("to_x", 0), action.get("to_y", 0),
            action.get("button", "left"),
        )

    # Keyboard
    elif action_type == "keyboard_type":
        from .actions.keyboard import keyboard_type
        return keyboard_type(action.get("text", ""))
    elif action_type == "keyboard_hotkey":
        from .actions.keyboard import keyboard_hotkey
        return keyboard_hotkey(action.get("keys", []))
    elif action_type == "keyboard_press":
        from .actions.keyboard import keyboard_press
        return keyboard_press(action.get("key", ""))

    # Apps & Commands
    elif action_type == "open_app":
        from .actions.apps import open_app
        return open_app(action.get("app", ""), action.get("args"))
    elif action_type == "run_command":
        from .actions.apps import run_command
        return run_command(action.get("command", ""), action.get("timeout", 30))

    # Clipboard
    elif action_type == "clipboard_get":
        from .actions.clipboard import clipboard_get
        return clipboard_get()
    elif action_type == "clipboard_set":
        from .actions.clipboard import clipboard_set
        return clipboard_set(action.get("text", ""))

    # Windows
    elif action_type == "window_list":
        from .actions.windows import window_list
        return window_list()
    elif action_type == "window_focus":
        from .actions.windows import window_focus
        return window_focus(action.get("title", ""))
    elif action_type == "window_resize":
        from .actions.windows import window_resize
        return window_resize(
            action.get("title", ""),
            action.get("x"), action.get("y"),
            action.get("width"), action.get("height"),
        )

    # OCR
    elif action_type == "ocr_screen":
        from .actions.ocr import ocr_screen
        return ocr_screen()
    elif action_type == "ocr_region":
        from .actions.ocr import ocr_region
        return ocr_region(
            action.get("x", 0), action.get("y", 0),
            action.get("width", 100), action.get("height", 100),
        )

    # Files
    elif action_type == "file_read":
        from .actions.files import file_read
        return file_read(action.get("path", ""))
    elif action_type == "file_write":
        from .actions.files import file_write
        return file_write(action.get("path", ""), action.get("content", ""))
    elif action_type == "file_list":
        from .actions.files import file_list
        return file_list(action.get("path", "."))

    # Wait
    elif action_type == "wait":
        ms = action.get("ms", 1000)
        time.sleep(ms / 1000.0)
        return {"success": True, "waited_ms": ms}

    else:
        return {"success": False, "error": f"Unknown action type: {action_type}"}
