"""Hash-pinned, fail-closed Lite6 reduced-safety commissioning.

The transaction in this module configures controller safety limits only.  It
has deliberately no motor-enable, state/mode, motion, or error-clear surface.
"""

from __future__ import annotations

import hashlib
import json
import math
import os
import stat
import struct
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Mapping, Sequence, Tuple

PROFILE_SCHEMA_VERSION = 1
LITE6_AXIS_COUNT = 6
LITE6_DEVICE_TYPE = 9
MAX_TCP_SPEED_MM_PER_SECOND = 250.0
MAX_JOINT_SPEED_RADIANS_PER_SECOND = math.radians(60.0)
LITE6_JOINT_LOWER_RADIANS = tuple(
    math.radians(value) for value in (-360, -150, -3.5, -360, -124, -360)
)
LITE6_JOINT_UPPER_RADIANS = tuple(
    math.radians(value) for value in (360, 150, 300, 360, 124, 360)
)
_PROFILE_KEYS = frozenset(
    (
        "schema_version",
        "robot_model",
        "axis_count",
        "device_type",
        "tcp_boundary_mm",
        "max_tcp_speed_mm_per_second",
        "max_joint_speed_radians_per_second",
        "joint_ranges_radians",
        "safety_boundary_enabled",
        "collision_rebound_enabled",
        "reduced_mode_enabled",
        "expected_robot_sn",
        "expected_firmware_version",
        "expected_world_offset_xyz_mm_rpy_degrees",
        "expected_tcp_offset_xyz_mm_rpy_degrees",
        "expected_tcp_load_kg",
        "expected_tcp_center_of_gravity_mm",
        "eye_in_hand_calibration_sha256",
        "motion_primitive_sha256",
        "minimum_collision_sensitivity",
    )
)


def _finite_vector(value: Any, length: int, name: str) -> Tuple[float, ...]:
    if not isinstance(value, list) or len(value) != length:
        raise ValueError("{} must contain exactly {} values".format(name, length))
    result = []
    for item in value:
        if isinstance(item, bool):
            raise ValueError("{} contains invalid values".format(name))
        try:
            number = float(item)
        except (TypeError, ValueError, OverflowError) as exc:
            raise ValueError("{} contains invalid values".format(name)) from exc
        if not math.isfinite(number):
            raise ValueError("{} contains invalid values".format(name))
        result.append(number)
    return tuple(result)


def _float32(value: float) -> float:
    """Canonicalize values to the controller's IEEE-754 wire precision."""

    return struct.unpack("!f", struct.pack("!f", float(value)))[0]


@dataclass(frozen=True)
class Lite6SafetyProfile:
    """The complete immutable controller-safety profile."""

    profile_sha256: str
    tcp_boundary_mm: Tuple[float, ...]
    max_tcp_speed_mm_per_second: float
    max_joint_speed_radians_per_second: float
    joint_ranges_radians: Tuple[float, ...]
    expected_robot_sn: str = ""
    expected_firmware_version: str = ""
    expected_world_offset_xyz_mm_rpy_degrees: Tuple[float, ...] = ()
    expected_tcp_offset_xyz_mm_rpy_degrees: Tuple[float, ...] = ()
    expected_tcp_load_kg: float = 0.0
    expected_tcp_center_of_gravity_mm: Tuple[float, ...] = ()
    eye_in_hand_calibration_sha256: str = ""
    motion_primitive_sha256: str = ""
    minimum_collision_sensitivity: int = 1

    @property
    def signature(self) -> Tuple[Any, ...]:
        return (
            self.tcp_boundary_mm,
            self.max_tcp_speed_mm_per_second,
            self.max_joint_speed_radians_per_second,
            self.joint_ranges_radians,
            1,
            0,
            1,
        )

    def public_profile(self) -> Mapping[str, Any]:
        return {
            "tcp_boundary_mm": list(self.tcp_boundary_mm),
            "max_tcp_speed_mm_per_second": self.max_tcp_speed_mm_per_second,
            "max_joint_speed_radians_per_second": (
                self.max_joint_speed_radians_per_second
            ),
            "joint_ranges_radians": list(self.joint_ranges_radians),
            "safety_boundary_enabled": True,
            "collision_rebound_enabled": False,
            "reduced_mode_enabled": True,
        }


def load_lite6_safety_profile(
    path: str,
    *,
    expected_sha256: str,
) -> Lite6SafetyProfile:
    """Load one root-owned, non-writable, hash-pinned JSON profile."""

    if (
        not isinstance(expected_sha256, str)
        or len(expected_sha256) != 64
        or any(character not in "0123456789abcdef" for character in expected_sha256)
    ):
        raise ValueError("safety profile SHA-256 is invalid")
    profile_path = Path(path)
    artifact_root = Path("/etc/labcobot")
    if not profile_path.is_absolute() or ".." in profile_path.parts:
        raise ValueError("safety profile path is unsafe")
    try:
        relative = profile_path.relative_to(artifact_root)
    except ValueError as exc:
        raise ValueError("safety profile must be below /etc/labcobot") from exc
    if not relative.parts:
        raise ValueError("safety profile must be below /etc/labcobot")
    metadata = profile_path.lstat()
    if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode):
        raise ValueError("safety profile must be a regular non-symlink file")
    if metadata.st_uid != 0:
        raise ValueError("safety profile must be owned by root")
    if metadata.st_mode & (stat.S_IWGRP | stat.S_IWOTH):
        raise ValueError("safety profile must not be group/other writable")
    descriptor = os.open(
        str(profile_path),
        os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0),
    )
    try:
        raw = os.read(descriptor, 64 * 1024 + 1)
        if len(raw) > 64 * 1024:
            raise ValueError("safety profile is too large")
        opened = os.fstat(descriptor)
        if (
            opened.st_dev != metadata.st_dev
            or opened.st_ino != metadata.st_ino
            or not stat.S_ISREG(opened.st_mode)
        ):
            raise ValueError("safety profile changed while opening")
    finally:
        os.close(descriptor)
    actual_sha256 = hashlib.sha256(raw).hexdigest()
    if actual_sha256 != expected_sha256:
        raise ValueError("safety profile SHA-256 does not match")
    try:
        document = json.loads(raw.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        raise ValueError("safety profile is not valid JSON") from exc
    if not isinstance(document, dict) or set(document) != _PROFILE_KEYS:
        raise ValueError("safety profile schema is invalid")
    if (
        document.get("schema_version") != PROFILE_SCHEMA_VERSION
        or document.get("robot_model") != "lite6"
        or document.get("axis_count") != LITE6_AXIS_COUNT
        or document.get("device_type") != LITE6_DEVICE_TYPE
        or document.get("safety_boundary_enabled") is not True
        or document.get("collision_rebound_enabled") is not False
        or document.get("reduced_mode_enabled") is not True
    ):
        raise ValueError("safety profile identity or required modes are invalid")
    robot_sn = document.get("expected_robot_sn")
    firmware = document.get("expected_firmware_version")
    if (
        not isinstance(robot_sn, str)
        or not 1 <= len(robot_sn) <= 64
        or any(
            character
            not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-"
            for character in robot_sn
        )
        or not isinstance(firmware, str)
        or not 1 <= len(firmware) <= 64
        or any(
            character
            not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.+-"
            for character in firmware
        )
    ):
        raise ValueError("safety profile controller identity is invalid")
    for name in ("eye_in_hand_calibration_sha256", "motion_primitive_sha256"):
        digest = document.get(name)
        if (
            not isinstance(digest, str)
            or len(digest) != 64
            or any(character not in "0123456789abcdef" for character in digest)
        ):
            raise ValueError("safety profile artifact binding is invalid")
    minimum_collision = document.get("minimum_collision_sensitivity")
    if type(minimum_collision) is not int or not 1 <= minimum_collision <= 5:
        raise ValueError("safety profile collision sensitivity is invalid")

    boundary = _finite_vector(document["tcp_boundary_mm"], 6, "TCP boundary")
    if any(not float(value).is_integer() for value in boundary):
        raise ValueError("safety profile TCP boundary must use exact integer mm")
    if any(boundary[index * 2] <= boundary[index * 2 + 1] for index in range(3)):
        raise ValueError("safety profile TCP boundary is invalid")
    tcp_speed = _finite_vector(
        [document["max_tcp_speed_mm_per_second"]],
        1,
        "TCP speed",
    )[0]
    joint_speed = _finite_vector(
        [document["max_joint_speed_radians_per_second"]],
        1,
        "joint speed",
    )[0]
    if not 0.0 < tcp_speed <= MAX_TCP_SPEED_MM_PER_SECOND:
        raise ValueError("safety profile TCP speed exceeds the ceiling")
    if not 0.0 < joint_speed <= MAX_JOINT_SPEED_RADIANS_PER_SECOND:
        raise ValueError("safety profile joint speed exceeds the ceiling")
    ranges = _finite_vector(
        document["joint_ranges_radians"],
        14,
        "joint ranges",
    )
    for index in range(6):
        lower = ranges[index * 2]
        upper = ranges[index * 2 + 1]
        if (
            lower >= upper
            or lower < LITE6_JOINT_LOWER_RADIANS[index]
            or upper > LITE6_JOINT_UPPER_RADIANS[index]
        ):
            raise ValueError("safety profile joint range exceeds Lite6 limits")
    if ranges[12:] != (0.0, 0.0):
        raise ValueError("safety profile dummy joint range is invalid")
    # XArmAPI is instantiated in degree mode.  The first three offset values
    # are millimetres and the final roll/pitch/yaw values are degrees.
    world_offset = _finite_vector(
        document["expected_world_offset_xyz_mm_rpy_degrees"],
        6,
        "world offset xyz-mm/rpy-degrees",
    )
    tcp_offset = _finite_vector(
        document["expected_tcp_offset_xyz_mm_rpy_degrees"],
        6,
        "TCP offset xyz-mm/rpy-degrees",
    )
    tcp_load = _finite_vector([document["expected_tcp_load_kg"]], 1, "TCP load")[0]
    if not 0.0 <= tcp_load <= 10.0:
        raise ValueError("safety profile TCP load is invalid")
    tcp_cog = _finite_vector(
        document["expected_tcp_center_of_gravity_mm"], 3, "TCP load center"
    )
    return Lite6SafetyProfile(
        profile_sha256=actual_sha256,
        tcp_boundary_mm=boundary,
        max_tcp_speed_mm_per_second=_float32(tcp_speed),
        max_joint_speed_radians_per_second=_float32(joint_speed),
        joint_ranges_radians=tuple(_float32(value) for value in ranges),
        expected_robot_sn=robot_sn,
        expected_firmware_version=firmware,
        expected_world_offset_xyz_mm_rpy_degrees=tuple(
            _float32(value) for value in world_offset
        ),
        expected_tcp_offset_xyz_mm_rpy_degrees=tuple(
            _float32(value) for value in tcp_offset
        ),
        expected_tcp_load_kg=_float32(tcp_load),
        expected_tcp_center_of_gravity_mm=tuple(_float32(value) for value in tcp_cog),
        eye_in_hand_calibration_sha256=document["eye_in_hand_calibration_sha256"],
        motion_primitive_sha256=document["motion_primitive_sha256"],
        minimum_collision_sensitivity=minimum_collision,
    )


def _require_command(result: Any, name: str, *, sequence: bool = False) -> None:
    if sequence:
        code = (
            result[0]
            if isinstance(result, (tuple, list)) and len(result) == 1
            else None
        )
    else:
        code = result
    if isinstance(code, bool) or type(code) is not int or code != 0:
        raise RuntimeError("xArm {} returned invalid code {!r}".format(name, code))


def _require_payload(result: Any, name: str) -> Any:
    if (
        not isinstance(result, (tuple, list))
        or len(result) != 2
        or isinstance(result[0], bool)
        or not isinstance(result[0], int)
        or result[0] != 0
    ):
        raise RuntimeError("xArm {} response is invalid".format(name))
    return result[1]


class Lite6SafetyBoundaryConfigurator:
    """Apply one validated profile through the narrow SDK safety surface."""

    def __init__(self, arm: Any, profile: Lite6SafetyProfile, lock: Any) -> None:
        self.arm = arm
        self.profile = profile
        self.lock = lock
        self.before_write = lambda: True
        self.last_transaction_writes_started = False

    @staticmethod
    def _pose_inside_profile(
        joints: Sequence[float],
        pose: Sequence[float],
        profile: Lite6SafetyProfile,
    ) -> bool:
        try:
            joint_values = _finite_vector(list(joints), 6, "current joints")
            pose_values = _finite_vector(list(pose), 6, "current TCP pose")
        except ValueError:
            return False
        ranges = profile.joint_ranges_radians
        if any(
            not ranges[index * 2] <= joint_values[index] <= ranges[index * 2 + 1]
            for index in range(6)
        ):
            return False
        boundary = profile.tcp_boundary_mm
        return all(
            boundary[index * 2 + 1] <= pose_values[index] <= boundary[index * 2]
            for index in range(3)
        )

    def _identity_binding_locked(self) -> bool:
        profile = self.profile
        try:
            robot_sn = _require_payload(self.arm.get_robot_sn(), "robot serial")
            firmware = str(getattr(self.arm, "version", "")).rsplit(",", 1)[-1]
            firmware = firmware[1:] if firmware[:1] in ("v", "V") else firmware
            expected_firmware = profile.expected_firmware_version
            expected_firmware = (
                expected_firmware[1:]
                if expected_firmware[:1] in ("v", "V")
                else expected_firmware
            )
            world_offset = tuple(
                _float32(value)
                for value in _finite_vector(
                    list(getattr(self.arm, "world_offset", None)),
                    6,
                    "world offset",
                )
            )
            tcp_offset = tuple(
                _float32(value)
                for value in _finite_vector(
                    list(getattr(self.arm, "tcp_offset", None)),
                    6,
                    "TCP offset",
                )
            )
            tcp_load = getattr(self.arm, "tcp_load", None)
            load_kg = _float32(float(tcp_load[0]))
            load_cog = tuple(
                _float32(value)
                for value in _finite_vector(list(tcp_load[1]), 3, "TCP load center")
            )
            sensitivity = getattr(self.arm, "collision_sensitivity", None)
        except (RuntimeError, ValueError, TypeError, IndexError, OverflowError):
            return False
        return bool(
            robot_sn == profile.expected_robot_sn
            and firmware == expected_firmware
            and world_offset == profile.expected_world_offset_xyz_mm_rpy_degrees
            and tcp_offset == profile.expected_tcp_offset_xyz_mm_rpy_degrees
            and load_kg == profile.expected_tcp_load_kg
            and load_cog == profile.expected_tcp_center_of_gravity_mm
            and type(sensitivity) is int
            and sensitivity >= profile.minimum_collision_sensitivity
        )

    def preflight(self) -> Mapping[str, bool]:
        """Read every controller invariant without changing controller state."""

        with self.lock:
            connected = bool(getattr(self.arm, "connected", False))
            axis = getattr(self.arm, "axis", None)
            device_type = getattr(self.arm, "device_type", None)
            try:
                state = _require_payload(self.arm.get_state(), "state")
                moving = self.arm.get_is_moving()
                error_warning = _require_payload(
                    self.arm.get_err_warn_code(),
                    "error/warning",
                )
                joints = _require_payload(
                    self.arm.get_servo_angle(is_radian=True),
                    "current joints",
                )
                pose = _require_payload(
                    self.arm.get_position(is_radian=True),
                    "current TCP pose",
                )
            except Exception:
                state = moving = error_warning = joints = pose = None
            motor_states = getattr(self.arm, "motor_enable_states", None)
            brake_states = getattr(self.arm, "motor_brake_states", None)
            motors_disabled = bool(
                isinstance(motor_states, (tuple, list))
                and len(motor_states) >= 6
                and all(
                    type(item) in (int, bool) and int(item) == 0
                    for item in motor_states[:6]
                )
            )
            identity = bool(
                type(axis) is int
                and axis == LITE6_AXIS_COUNT
                and type(device_type) is int
                and device_type == LITE6_DEVICE_TYPE
            )
            healthy = bool(
                isinstance(error_warning, (tuple, list))
                and len(error_warning) >= 2
                and type(error_warning[0]) is int
                and type(error_warning[1]) is int
                and error_warning[0] == 0
                and error_warning[1] == 0
            )
            stopped = type(state) is int and state == 4
            stationary = moving is False
            mode_locked = (
                type(getattr(self.arm, "mode", None)) is int
                and getattr(self.arm, "mode", None) == 0
            )
            brakes_engaged = bool(
                isinstance(brake_states, (tuple, list))
                and len(brake_states) >= 6
                and all(
                    type(item) in (int, bool) and int(item) == 0
                    for item in brake_states[:6]
                )
            )
            pose_inside_profile = (
                self._pose_inside_profile(joints, pose, self.profile)
                if joints is not None and pose is not None
                else False
            )
            controller_binding_verified = self._identity_binding_locked()
            ready = bool(
                connected
                and identity
                and healthy
                and stopped
                and motors_disabled
                and stationary
                and mode_locked
                and brakes_engaged
                and pose_inside_profile
                and controller_binding_verified
            )
            return {
                "ready": ready,
                "connected": connected,
                "healthy": healthy,
                "stopped": stopped,
                "motors_disabled": motors_disabled,
                "stationary": stationary,
                "identity_verified": identity,
                "mode_locked": mode_locked,
                "brakes_engaged": brakes_engaged,
                "pose_inside_profile": pose_inside_profile,
                "controller_binding_verified": controller_binding_verified,
            }

    def readback(self) -> Mapping[str, Any]:
        with self.lock:
            return self._readback_locked()

    def verify_for_motion_locked(self) -> Mapping[str, Any]:
        """Verify the pinned profile while the caller holds ``self.lock``.

        The real motion adapter invokes this immediately before motor-enable
        and keeps the same shared SDK lock held through that command.  Keeping
        this method lock-free is deliberate: acquiring the non-reentrant
        controller lock here would deadlock the arming path.
        """

        preflight = dict(self._preflight_locked())
        readback = dict(self._readback_locked())
        verified = bool(
            preflight.get("ready") is True and readback.get("verified") is True
        )
        if not verified:
            raise RuntimeError(
                "Pinned Lite6 safety profile is not ready for motor enable"
            )
        return {
            "verified": True,
            "preflight": preflight,
            "readback": readback,
            "profile_sha256": self.profile.profile_sha256,
        }

    def configure(self) -> Mapping[str, Any]:
        """Set limits in reviewed order and require exact final readback."""

        with self.lock:
            self.last_transaction_writes_started = False
            preflight = self._preflight_locked()
            if preflight["ready"] is not True:
                raise RuntimeError("xArm safety configuration preflight failed")
            profile = self.profile
            operations = (
                (
                    "reduced TCP boundary",
                    lambda: self.arm.set_reduced_tcp_boundary(
                        list(profile.tcp_boundary_mm)
                    ),
                ),
                (
                    "reduced TCP speed",
                    lambda: self.arm.set_reduced_max_tcp_speed(
                        profile.max_tcp_speed_mm_per_second
                    ),
                ),
                (
                    "reduced joint speed",
                    lambda: self.arm.set_reduced_max_joint_speed(
                        profile.max_joint_speed_radians_per_second,
                        is_radian=True,
                    ),
                ),
                (
                    "reduced joint ranges",
                    lambda: self.arm.set_reduced_joint_range(
                        list(profile.joint_ranges_radians),
                        is_radian=True,
                    ),
                ),
                ("fence mode", lambda: self.arm.set_fence_mode(True), True),
                (
                    "collision rebound",
                    lambda: self.arm.set_collision_rebound(False),
                    True,
                ),
                ("reduced mode", lambda: self.arm.set_reduced_mode(True), False),
            )
            normalized_operations = []
            for operation in operations:
                if len(operation) == 2:
                    normalized_operations.append((operation[0], operation[1], False))
                else:
                    normalized_operations.append(operation)
            try:
                current = self._readback_locked()
                if current["verified"] is True:
                    return current
                if current["reduced_mode_enabled"] is True:
                    raise RuntimeError(
                        "active reduced configuration differs from pinned profile"
                    )
                for name, callback, sequence in normalized_operations:
                    if self.before_write() is not True:
                        raise RuntimeError("safety configuration generation changed")
                    # Conservatively treat the transaction as partial before
                    # entering the SDK call: a transport failure can hide
                    # whether the controller accepted the command.
                    self.last_transaction_writes_started = True
                    _require_command(callback(), name, sequence=sequence)
                if self.before_write() is not True:
                    raise RuntimeError("safety configuration generation changed")
                readback = self._readback_locked()
                if readback["verified"] is not True:
                    raise RuntimeError("xArm safety configuration readback mismatch")
                return readback
            except Exception as original_error:
                # A failed read or partial safety-limit write must leave the
                # controller stopped and motors disabled.  These are fail-safe
                # commands, never an unlock, motion, or error-clear operation.
                try:
                    self._fail_safe_locked()
                except Exception as fail_safe_error:
                    raise RuntimeError(
                        "xArm safety configuration failed and fail-safe lock "
                        "could not be confirmed"
                    ) from fail_safe_error
                raise original_error

    def _fail_safe_locked(self) -> None:
        failures = []
        for name, callback in (
            ("state 4", lambda: self.arm.set_state(4)),
            (
                "motor disable",
                lambda: self.arm.motion_enable(enable=False),
            ),
        ):
            try:
                _require_command(callback(), name)
            except Exception as exc:
                failures.append("{}: {}".format(name, type(exc).__name__))
        if failures:
            raise RuntimeError(
                "xArm fail-safe commands failed: {}".format(", ".join(failures))
            )

    def _preflight_locked(self) -> Mapping[str, bool]:
        # Keep all reads in one SDK critical section without recursively
        # acquiring the metric-source lock.
        connected = bool(getattr(self.arm, "connected", False))
        axis = getattr(self.arm, "axis", None)
        device_type = getattr(self.arm, "device_type", None)
        state = _require_payload(self.arm.get_state(), "state")
        moving = self.arm.get_is_moving()
        if not isinstance(moving, bool):
            raise RuntimeError("xArm moving-state response is invalid")
        error_warning = _require_payload(self.arm.get_err_warn_code(), "error/warning")
        joints = _require_payload(
            self.arm.get_servo_angle(is_radian=True), "current joints"
        )
        pose = _require_payload(
            self.arm.get_position(is_radian=True), "current TCP pose"
        )
        motor_states = getattr(self.arm, "motor_enable_states", None)
        brake_states = getattr(self.arm, "motor_brake_states", None)
        motors_disabled = bool(
            isinstance(motor_states, (tuple, list))
            and len(motor_states) >= 6
            and all(
                type(item) in (int, bool) and int(item) == 0
                for item in motor_states[:6]
            )
        )
        identity = bool(
            type(axis) is int
            and axis == LITE6_AXIS_COUNT
            and type(device_type) is int
            and device_type == LITE6_DEVICE_TYPE
        )
        healthy = bool(
            isinstance(error_warning, (tuple, list))
            and len(error_warning) >= 2
            and type(error_warning[0]) is int
            and type(error_warning[1]) is int
            and error_warning[0] == 0
            and error_warning[1] == 0
        )
        result = {
            "connected": connected,
            "healthy": healthy,
            "stopped": type(state) is int and state == 4,
            "motors_disabled": motors_disabled,
            "stationary": moving is False,
            "identity_verified": identity,
            "mode_locked": type(getattr(self.arm, "mode", None)) is int
            and getattr(self.arm, "mode", None) == 0,
            "brakes_engaged": bool(
                isinstance(brake_states, (tuple, list))
                and len(brake_states) >= 6
                and all(
                    type(item) in (int, bool) and int(item) == 0
                    for item in brake_states[:6]
                )
            ),
            "pose_inside_profile": self._pose_inside_profile(
                joints, pose, self.profile
            ),
            "controller_binding_verified": self._identity_binding_locked(),
        }
        result["ready"] = all(result.values())
        return result

    def _readback_locked(self) -> Mapping[str, Any]:
        mode = _require_payload(self.arm.get_reduced_mode(), "reduced mode")
        states = _require_payload(
            self.arm.get_reduced_states(is_radian=True),
            "reduced states",
        )
        result = {
            "verified": False,
            "tcp_boundary_mm": None,
            "max_tcp_speed_mm_per_second": None,
            "max_joint_speed_radians_per_second": None,
            "joint_ranges_radians": None,
            "safety_boundary_enabled": False,
            "collision_rebound_enabled": False,
            "reduced_mode_enabled": False,
        }
        if not isinstance(states, (tuple, list)) or len(states) != 7:
            return result
        try:
            boundary = _finite_vector(list(states[1]), 6, "readback boundary")
            ranges = _finite_vector(list(states[4]), 14, "readback joint ranges")
            tcp_speed = _finite_vector([states[2]], 1, "readback TCP speed")[0]
            joint_speed = _finite_vector([states[3]], 1, "readback joint speed")[0]
        except ValueError:
            return result
        result.update(
            {
                "tcp_boundary_mm": list(boundary),
                "max_tcp_speed_mm_per_second": tcp_speed,
                "max_joint_speed_radians_per_second": joint_speed,
                "joint_ranges_radians": list(ranges),
                "safety_boundary_enabled": type(states[5]) is int and states[5] == 1,
                "collision_rebound_enabled": type(states[6]) is int and states[6] == 1,
                "reduced_mode_enabled": type(mode) is int
                and mode == 1
                and type(states[0]) is int
                and states[0] == 1,
            }
        )
        expected = self.profile
        result["verified"] = bool(
            tuple(result["tcp_boundary_mm"]) == expected.tcp_boundary_mm
            and result["max_tcp_speed_mm_per_second"]
            == expected.max_tcp_speed_mm_per_second
            and result["max_joint_speed_radians_per_second"]
            == expected.max_joint_speed_radians_per_second
            and tuple(result["joint_ranges_radians"]) == expected.joint_ranges_radians
            and result["safety_boundary_enabled"] is True
            and result["collision_rebound_enabled"] is False
            and result["reduced_mode_enabled"] is True
        )
        return result


__all__ = [
    "Lite6SafetyBoundaryConfigurator",
    "Lite6SafetyProfile",
    "load_lite6_safety_profile",
]
