#!/usr/bin/env python3
"""Read-only inventory and deliberately narrow Isaac ROS 3.2 prerequisite check.

Python 3.9+, standard library only. No shell, subprocess, network or file writes.
This is an editorial aid, not an NVIDIA compatibility or installation tool.
"""
import argparse
import json
import os
import platform
import re
from pathlib import Path

REVIEWED = "2026-12-04"
PROFILE = "release-3.2"
# Exact L4T mappings in NVIDIA's JetPack archive, not a prefix/range match.
L4T_TO_JETPACK = {"36.4.0": "6.1", "36.4.3": "6.2"}
FIELDS = {"scope", "architecture", "model", "os_id", "os_version",
          "l4t_version", "ros_distro", "container_marker"}
LIMITS = [
    "Only the archived release-3.2 Orin Nano host prerequisite profile is checked.",
    "A match does not validate CUDA, TensorRT, Docker, GPU access, sensors or ROS nodes.",
    "ROS_DISTRO identifies the current shell, not all installed ROS distributions.",
    "Host scope is declared by the caller; container markers are incomplete heuristics.",
    "No performance, security, firmware, free-memory or package-specific check is made.",
]


def read_optional(path):
    try:
        return Path(path).read_text(errors="replace").replace("\x00", "").strip()
    except (OSError, UnicodeError):
        return None


def parse_os_release(text):
    values = {}
    for line in (text or "").splitlines():
        key, sep, value = line.partition("=")
        if sep and key in {"ID", "VERSION_ID"}:
            values[key] = value.strip().strip("\"'")
    return values


def parse_l4t(text):
    match = re.search(r"#\s*R(\d+)\s*\(release\),\s*REVISION:\s*(\d+(?:\.\d+)?)", text or "")
    if not match:
        return None
    version = match.group(1) + "." + match.group(2)
    return version + ".0" if version.count(".") == 1 else version


def collect(scope):
    release = parse_os_release(read_optional("/etc/os-release"))
    return {
        "scope": scope,
        "architecture": platform.machine().lower(),
        "model": read_optional("/proc/device-tree/model"),
        "os_id": release.get("ID"),
        "os_version": release.get("VERSION_ID"),
        "l4t_version": parse_l4t(read_optional("/etc/nv_tegra_release")),
        "ros_distro": os.environ.get("ROS_DISTRO") or None,
        "container_marker": Path("/.dockerenv").exists() or Path("/run/.containerenv").exists(),
    }


def validate_inventory(data):
    if not isinstance(data, dict):
        raise ValueError("Inventory must be a JSON object.")
    extra = set(data) - FIELDS
    if extra:
        raise ValueError("Unknown inventory fields: " + ", ".join(sorted(extra)))
    for field in FIELDS - {"container_marker"}:
        value = data.get(field)
        if value is not None and not isinstance(value, str):
            raise ValueError(field + " must be a string or null.")
    if data.get("container_marker") is not None and type(data["container_marker"]) is not bool:
        raise ValueError("container_marker must be boolean or null.")
    if data.get("scope") not in {"host", "container", "unknown", None}:
        raise ValueError("scope must be host, container or unknown.")


def assess(data, target):
    validate_inventory(data)
    checks = []

    def add(name, status, detail):
        checks.append({"check": name, "status": status, "detail": detail})

    if target != PROFILE:
        add("target_release", "outside_profile", "Use the versioned NVIDIA matrix for " + target + "; this tool makes no support judgment.")
    elif data.get("scope") != "host" or data.get("container_marker") is True:
        add("host_scope", "unknown", "Collect again on the Jetson host; container OS/L4T files cannot certify its host.")
    else:
        for field, expected in (("architecture", "aarch64"), ("os_id", "ubuntu"), ("os_version", "22.04")):
            observed = data.get(field)
            status = "unknown" if not observed else ("match" if observed == expected else "mismatch")
            add(field, status, "Expected " + expected + "; observed " + str(observed))
        model = data.get("model")
        model_match = bool(model and re.search(r"\bjetson\s+orin\s+nano\b", model, re.I))
        add("model", "match" if model_match else "unknown" if not model else "outside_profile",
            "Expected an Orin Nano model; model text does not establish RAM capacity or Super power mode.")
        l4t = data.get("l4t_version")
        if l4t in L4T_TO_JETPACK:
            add("l4t", "match", "L4T " + l4t + " maps to JetPack " + L4T_TO_JETPACK[l4t] + ".")
        elif not l4t or (isinstance(l4t, str) and l4t.startswith("36.")):
            add("l4t", "unknown", "No exact reviewed mapping; verify the JetPack patch and release-3.2 documentation.")
        else:
            add("l4t", "mismatch", "This L4T version is outside the reviewed JetPack 6.1/6.2 profile.")

    statuses = {c["status"] for c in checks}
    if "mismatch" in statuses:
        result = "profile_mismatch"
    elif "outside_profile" in statuses:
        result = "outside_profile"
    elif "unknown" in statuses:
        result = "incomplete"
    else:
        result = "host_prerequisites_match"
    ros = data.get("ros_distro")
    return {
        "reviewed_on": REVIEWED,
        "requested_isaac_ros_release": target,
        "profile_result": result,
        "runtime_readiness": "not_tested",
        "inventory": data,
        "checks": checks,
        "shell_ros_note": (
            "No ROS distribution sourced; this is normal before entering the dev container."
            if not ros else
            "Current shell reports " + ros + "; release-3.2 procedures require Humble in the runtime."
        ),
        "limits": LIMITS,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--scope", choices=["host", "container", "unknown"], default="unknown",
                        help="Declared observation location; default never assumes a host.")
    parser.add_argument("--target", default=PROFILE, help="Intended Isaac ROS release, not an installed-version assertion.")
    parser.add_argument("--fixture", type=Path, help="Read synthetic/input JSON instead of probing this machine.")
    args = parser.parse_args()
    try:
        data = json.loads(args.fixture.read_text()) if args.fixture else collect(args.scope)
        report = assess(data, args.target)
        report["input_kind"] = "provided_json_not_observed_hardware" if args.fixture else "local_read_only_inventory"
    except (OSError, ValueError) as error:
        parser.exit(2, "Invalid inventory: " + str(error) + "\n")
    print(json.dumps(report, indent=2, ensure_ascii=False))
    # 0 = reviewed prerequisite match, 1 = review required, 2 = malformed input.
    return 0 if report["profile_result"] == "host_prerequisites_match" else 1


if __name__ == "__main__":
    raise SystemExit(main())
