from __future__ import annotations

import sys
from pathlib import Path


ROOT = next(parent for parent in Path(__file__).resolve().parents if (parent / "cosmic_driver").is_dir())
sys.path.insert(0, str(ROOT))

from cosmic_driver import CosmicPySDK, FW_INTERFACE_ALREADY_INITIALIZED, I2cTransferRate, I3cDriveStrength, I3cOpenDrainTransferRate, I3cPushPullRate, I3cTransferFlags, SUCCESS
from example_helpers import print_device_info, print_payload, assert_status


def main() -> None:
    with CosmicPySDK(timeout_ms=2000) as device:
        if not device.open():
            raise RuntimeError("Failed to connect to a Binho device.")

        status, info = device.get_device_info()
        assert_status(status, "get_device_info")
        assert info is not None
        print_device_info(info)

        status, _ = device.i3c_set_bus_voltage(3300)
        assert_status(status, "i3c_set_bus_voltage")

        status, _ = device.i3c_controller_init(
            I3cPushPullRate.PUSH_PULL_3_125_MHz_DC_31_25,
            I3cOpenDrainTransferRate.OPEN_DRAIN_1_MHz,
            I2cTransferRate.FAST_MODE,
            I3cDriveStrength.STANDARD,
        )
        assert_status(status, "i3c_controller_init", (SUCCESS, FW_INTERFACE_ALREADY_INITIALIZED))

        status, _ = device.i3c_init_bus()
        assert_status(status, "i3c_init_bus")

        status, _ = device.i3c_hdr_ddr_write(0x08, 0x04, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
        assert_status(status, "i3c_hdr_ddr_write")

        status, _ = device.i3c_sdr_write(0x08, [0x00], [], I3cTransferFlags.I3C_XFER_START_WITH_7E)
        assert_status(status, "i3c_sdr_write(pointer reset)")

        status, payload = device.i3c_hdr_ddr_read(0x08, 0x80, 10)
        assert_status(status, "i3c_hdr_ddr_read")
        assert payload is not None
        print_payload("Hdr-Ddr read:", payload)


if __name__ == "__main__":
    main()
