#!/usr/bin/env python3
"""
conftest.py — pytest fixtures for the saltybot_can_e2e_test suite.

No ROS2 node infrastructure is started; all tests run purely in Python.
"""

import sys
import os

# Ensure the package root is on sys.path so relative imports work when running
# pytest directly from the saltybot_can_e2e_test/ directory.
_pkg_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _pkg_root not in sys.path:
    sys.path.insert(0, _pkg_root)

# Also add the saltybot_can_bridge package so we can import balance_protocol.
_bridge_pkg = os.path.join(
    os.path.dirname(_pkg_root), "saltybot_can_bridge"
)
if _bridge_pkg not in sys.path:
    sys.path.insert(0, _bridge_pkg)

import pytest

from saltybot_can_e2e_test.can_mock import MockCANBus
from saltybot_can_e2e_test.protocol_defs import (
    VESC_CAN_ID_LEFT,
    VESC_CAN_ID_RIGHT,
)


# ---------------------------------------------------------------------------
# Core fixtures
# ---------------------------------------------------------------------------


@pytest.fixture(scope="function")
def mock_can_bus():
    """
    Provide a fresh MockCANBus instance per test function.
    The bus is automatically shut down after each test.
    """
    bus = MockCANBus(loopback=False)
    yield bus
    bus.shutdown()


@pytest.fixture(scope="function")
def loopback_can_bus():
    """
    MockCANBus in loopback mode — sent frames are also queued for recv.
    Useful for testing round-trip behaviour without a second node.
    """
    bus = MockCANBus(loopback=True)
    yield bus
    bus.shutdown()


@pytest.fixture(scope="function")
def bridge_components():
    """
    Return the balance_protocol encode/decode callables and a fresh mock bus.

    Yields a dict with keys:
      bus         — MockCANBus instance
      encode_vel  — encode_velocity_cmd(left, right) → bytes
      encode_mode — encode_mode_cmd(mode) → bytes
      encode_estop — encode_estop_cmd(stop) → bytes
      decode_vesc  — decode_vesc_state(data) → VescStateTelemetry
    """
    from saltybot_can_bridge.balance_protocol import (
        encode_velocity_cmd,
        encode_mode_cmd,
        encode_estop_cmd,
        decode_vesc_state,
        decode_battery_telem,
        decode_imu_telem,
    )

    bus = MockCANBus(loopback=False)
    yield {
        "bus": bus,
        "encode_vel": encode_velocity_cmd,
        "encode_mode": encode_mode_cmd,
        "encode_estop": encode_estop_cmd,
        "decode_vesc": decode_vesc_state,
        "decode_battery": decode_battery_telem,
        "decode_imu": decode_imu_telem,
        "left_vesc_id": VESC_CAN_ID_LEFT,
        "right_vesc_id": VESC_CAN_ID_RIGHT,
    }
    bus.shutdown()
