#!/usr/bin/env python3
# This software is distributed under the terms of the MIT License.
# Copyright (c) 2025 Dmitry Ponomarev.
# Author: Dmitry Ponomarev <ponomarevda96@gmail.com>

import time
from typing import Any, Union

from tsugite.backend.backend import BaseBackend

class DummyBackend(BaseBackend):
    """Framework-independent communicator mock.
    Call `tick(dt)` periodically (e.g. every 0.01 s at 100 Hz).
    Internally emits Heartbeat messages once per second.
    """

    def __init__(self):
        self._subscribers = {}

        self._heartbeat_counter = 0
        self._last_heartbeat = time.time()

    def subscribe(self, topic: str, callback, node_id=None):
        """Register callback for a given topic."""
        self._subscribers.setdefault(topic, []).append(callback)

    def get_info(self, node_id: int) -> dict:
        return {}

    def read_param(self, param_name: str, node_id):
        """Get parameter by name (always returns None)."""
        return None

    def write_param(self, param_name: str, value: Any, node_id: Union[int, None]) -> Union[bool, int, float, str, None]:
        """Write a parameter value to the node."""
        pass

    def register_periodic_publisher(self, topic: str, field: str, frequency: float = 10.0) -> None:
        """Register a periodic message publisher."""
        pass

    def update_periodic_publisher(self, topic: str, field: str, value) -> None:
        """Update the value of a periodic message publisher."""
        pass

    def tick(self, dt: float):
        """Called periodically (e.g., 100 Hz)."""
        recv_msgs = {}

        # Emit Heartbeat every second
        now = time.time()
        if now - self._last_heartbeat >= 1.0:
            self._heartbeat_counter += 1
            self._last_heartbeat = now
            recv_msgs["Heartbeat"] = {"uptime_sec": self._heartbeat_counter}

        for recv_msg in recv_msgs:
            for cb in self._subscribers.get(recv_msg, []):
                cb(recv_msg, recv_msgs[recv_msg])
