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
from example_helpers import print_device_info, print_target_device_table, assert_status


def print_table(device: CosmicPySDK, stage: str) -> None:
    status, table = device.i3c_get_device_table()
    assert_status(status, f"i3c_get_device_table({stage})")
    assert table is not None
    print_target_device_table(table)


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_init_bus()
        assert_status(status, "i3c_init_bus")

        status, _ = device.i3c_reset_bus()
        assert_status(status, "i3c_reset_bus before SETDASA")
        status, _ = device.i3c_ccc_setdasa(0x69, 0x0B)
        assert_status(status, "i3c_ccc_setdasa(0x69 -> 0x0B)")
        status, _ = device.i3c_ccc_setdasa(0x6B, 0x0C)
        assert_status(status, "i3c_ccc_setdasa(0x6B -> 0x0C)")
        print_table(device, "after SETDASA")

        status, _ = device.i3c_reset_bus()
        assert_status(status, "i3c_reset_bus before SETAASA")
        status, _ = device.i3c_ccc_setaasa([0x69, 0x6B])
        assert_status(status, "i3c_ccc_setaasa")
        print_table(device, "after SETAASA")

        status, _ = device.i3c_reset_bus()
        assert_status(status, "i3c_reset_bus before ENTDAA")
        status, _ = device.i3c_ccc_entdaa()
        assert_status(status, "i3c_ccc_entdaa")
        print_table(device, "after ENTDAA")

        status, _ = device.i3c_reset_bus()
        assert_status(status, "i3c_reset_bus before SETNEWDA")
        status, _ = device.i3c_init_bus()
        assert_status(status, "i3c_init_bus before SETNEWDA")
        status, _ = device.i3c_ccc_setnewda(0x08, 0x0B)
        assert_status(status, "i3c_ccc_setnewda(0x08 -> 0x0B)")
        status, _ = device.i3c_ccc_setnewda(0x09, 0x0C)
        assert_status(status, "i3c_ccc_setnewda(0x09 -> 0x0C)")
        print_table(device, "after SETNEWDA")


if __name__ == "__main__":
    main()
