"""{{ module_description }}

This module implements a MADSci REST node for {{ module_name }}.

Generated by: madsci new module --template module/basic
Template version: {{ template_version }}
"""

import argparse
import sys
from typing import Literal

from madsci.node_module import ActionHandler, ActionRequest, ActionResult, RestNode

from {{ module_name }}_types import {{ module_name | pascal_case }}NodeConfig

# Import interfaces - switch between real and fake based on configuration
from {{ module_name }}_interface import {{ module_name | pascal_case }}Interface
from {{ module_name }}_fake_interface import {{ module_name | pascal_case }}FakeInterface


class {{ module_name | pascal_case }}Node(RestNode):
    """{{ module_description }}

    This node provides a REST API for controlling the {{ module_name }} device.
    """

    config: {{ module_name | pascal_case }}NodeConfig = {{ module_name | pascal_case }}NodeConfig()
    config_model = {{ module_name | pascal_case }}NodeConfig

    def __init__(
        self,
        interface_type: Literal["real", "fake"] = "real",
        **kwargs,
    ) -> None:
        """Initialize the {{ module_name }} node.

        Args:
            interface_type: Which interface to use ("real" or "fake").
            **kwargs: Additional arguments passed to RestNode.
        """
        super().__init__(**kwargs)
        self.interface_type = interface_type
        self._interface = None

    def startup_handler(self) -> None:
        """Initialize the interface on node startup."""
        if self.interface_type == "fake":
            self._interface = {{ module_name | pascal_case }}FakeInterface()
        else:
            self._interface = {{ module_name | pascal_case }}Interface()

        self._interface.connect()

    def shutdown_handler(self) -> None:
        """Clean up resources on node shutdown."""
        if self._interface:
            self._interface.disconnect()

    @ActionHandler(
        description="Perform an example action",
    )
    def example_action(self, action: ActionRequest) -> ActionResult:
        """Execute an example action.

        This is a placeholder action. Replace with your actual device operations.

        Args:
            action: The action request with parameters.

        Returns:
            ActionResult indicating success or failure.
        """
        try:
            # Get optional message parameter
            message = action.args.get("message", "Hello from {{ module_name }}!")

            # Call the interface method
            result = self._interface.do_something(message)

            return ActionResult.succeeded(
                action=action,
                message=f"Action completed: {result}",
                data={"result": result},
            )
        except Exception as e:
            return ActionResult.failed(
                action=action,
                message=f"Action failed: {e}",
            )


def main() -> None:
    """Entry point for the {{ module_name }} node."""
    parser = argparse.ArgumentParser(description="{{ module_description }}")
    parser.add_argument(
        "--fake",
        action="store_true",
        help="Use fake interface for testing without hardware",
    )
    parser.add_argument(
        "--port",
        type=int,
        default={{ port }},
        help="Port to run the node on (default: {{ port }})",
    )
    args = parser.parse_args()

    interface_type = "fake" if args.fake else "real"

    node = {{ module_name | pascal_case }}Node(interface_type=interface_type)
    node.config.node_url = f"http://localhost:{args.port}/"
    node.start_node()


if __name__ == "__main__":
    main()
