import os
import pathlib
import pytest

# Hardware + babylin + smoke: this is the canonical end-to-end schedule flow
pytestmark = [pytest.mark.hardware, pytest.mark.babylin, pytest.mark.smoke]

WORKSPACE_ROOT = pathlib.Path(__file__).resolve().parents[1]


def test_babylin_sdk_example_flow(config, lin, rp):
    """
    Title: BabyLIN SDK Example Flow - Open, Load SDF, Start Schedule, Rx Timeout

    Description:
        Mirrors the vendor example flow: discover/open, load SDF, start a
        schedule, and attempt a receive. Validates that the adapter can perform
        the essential control sequence without exceptions and that the receive
        path is operational even if it times out.

    Requirements: REQ-HW-OPEN, REQ-HW-SDF, REQ-HW-SCHEDULE

    Preconditions:
        - ECU_TESTS_CONFIG points to a hardware YAML with interface.sdf_path and schedule_nr
        - BabyLIN_library.py and native libs placed per vendor/README.md

    Test Steps:
        1. Verify hardware config requests the BabyLIN SDK with SDF path
        2. Connect via fixture (opens device, loads SDF, starts schedule)
        3. Try to receive a frame with a short timeout
        4. Assert no crash; accept None or a LinFrame (environment-dependent)

    Expected Result:
        - No exceptions during open/load/start
        - Receive returns None (timeout) or a LinFrame
    """
    # Step 1: Ensure config is set for hardware with SDK wrapper
    assert config.interface.type == "babylin"
    assert config.interface.sdf_path is not None
    rp("sdf_path", str(config.interface.sdf_path))
    rp("schedule_nr", int(config.interface.schedule_nr))

    # Step 3: Attempt a short receive to validate RX path while schedule runs
    rx = lin.receive(timeout=0.2)
    rp("receive_result", "timeout" if rx is None else "frame")

    # Step 4: Accept timeout or a valid frame object depending on bus activity
    assert rx is None or hasattr(rx, "id")
