"""Read-only xArm controller-firmware commissioning status.

LabCobot application OTA never updates controller firmware.  This module only
compares bounded cached telemetry with the version from the root-owned,
hash-pinned Lite6 safety profile.  It has no xArm SDK or command surface and
cannot grant motion authority.
"""

from __future__ import annotations

import re
from typing import Any, Mapping

SCHEMA = "labcobot.xarm-controller-firmware-status.v1"
MAINTENANCE_ACTION = "supervised_vendor_firmware_maintenance"
_VERSION = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,63}")


def normalize_controller_firmware(value: Any) -> str:
    """Return one bounded version only, never controller identity material."""

    if not isinstance(value, str) or len(value) > 255:
        return ""
    candidate = value.rsplit(",", 1)[-1].strip()
    if candidate[:1] in ("v", "V"):
        candidate = candidate[1:]
    if not _VERSION.fullmatch(candidate):
        return ""
    return candidate


def controller_firmware_status(
    expected_version: Any,
    xarm_snapshot: Any,
) -> Mapping[str, Any]:
    """Evaluate commissioned-versus-observed firmware without side effects."""

    commissioned = normalize_controller_firmware(expected_version)
    xarm = xarm_snapshot if isinstance(xarm_snapshot, Mapping) else {}
    metrics = xarm.get("metrics")
    metrics = metrics if isinstance(metrics, Mapping) else {}
    controller = metrics.get("controller")
    controller = controller if isinstance(controller, Mapping) else {}
    observed = normalize_controller_firmware(controller.get("firmware_version"))

    blockers = []
    if not commissioned:
        blockers.append("controller_firmware_not_commissioned")
    telemetry_ready = bool(
        xarm.get("configured") is True
        and xarm.get("available") is True
        and xarm.get("connected") is True
        and xarm.get("healthy") is True
        and xarm.get("fresh") is True
        and xarm.get("axis_count") == 6
        and xarm.get("device_type") == 9
    )
    if not telemetry_ready or not observed:
        blockers.append("controller_firmware_unavailable")
    elif commissioned and observed != commissioned:
        blockers.append("controller_firmware_mismatch")

    matches = bool(commissioned and observed and commissioned == observed)
    ready = bool(matches and not blockers)
    maintenance_required = "controller_firmware_mismatch" in blockers
    return {
        "schema": SCHEMA,
        "configured": bool(commissioned),
        "ready": ready,
        "commissioned_version": commissioned,
        "observed_version": observed,
        "matches": matches,
        "maintenance_required": maintenance_required,
        "maintenance_action": MAINTENANCE_ACTION if maintenance_required else "",
        "motion_authority": "none",
        "blockers": blockers,
    }
