#!/usr/bin/python3
"""Capture kernel-exported hwmon inputs and driver bindings without configuring them."""

import argparse
from datetime import datetime, timezone
import errno
import json
import os
from pathlib import Path
import re
import sys
import time


INPUTS = re.compile(r"(fan|temp|in)\d+_input")
INTEGER = re.compile(r"-?[0-9]+")
UNITS = {"fan": ("RPM", "RPM", 1), "temp": ("m°C", "°C", 1000), "in": ("mV", "V", 1000)}
GPU_CHIPS = {"amdgpu", "radeon", "nouveau", "nvidia"}


def read(path):
    try:
        with path.open(encoding="utf-8") as stream:
            value = stream.read(4097)
    except OSError as error:
        status = {
            errno.ENOENT: "not_exported",
            errno.EACCES: "access_denied",
            errno.EPERM: "access_denied",
            errno.ENODATA: "no_data",
        }.get(error.errno, "read_error")
        return {"status": status, "errno": error.errno, "error": error.strerror}
    except UnicodeError:
        return {"status": "invalid_encoding"}
    if len(value) > 4096:
        return {"status": "value_too_long"}
    return {"status": "read", "value": value.strip()}


def link(path):
    try:
        return {"status": "resolved", "path": str(path.resolve(strict=True))}
    except (OSError, RuntimeError) as error:
        err = getattr(error, "errno", None)
        return {"status": "not_exported" if err == errno.ENOENT else "resolve_error", "errno": err}


def directory(path):
    try:
        return sorted(path.iterdir()), {"status": "read"}
    except OSError as error:
        return [], {"status": "directory_unavailable", "errno": error.errno, "error": error.strerror}


def binding(node, include_resources=False):
    driver = link(node / "driver")
    result = {"id": node.name, "path": link(node), "driver": driver, "modalias": read(node / "modalias")}
    if include_resources:
        result["resources"] = read(node / "resources")
        result["firmware_node"] = link(node / "firmware_node")
    if node.name.startswith(("PNP0C02:", "PNP0C14:")):
        result["namespace_path"] = read(node / "path")
        result["device_status"] = read(node / "status")
    return result


def sample(node, kind):
    raw_unit, unit, divisor = UNITS[kind]
    channel = node.name.removesuffix("_input")
    raw = read(node)
    data = {"attribute": node.name, "raw": raw, "raw_unit": raw_unit,
            "label": read(node.with_name(channel + "_label")), "captured_monotonic_ns": str(time.monotonic_ns())}
    if kind in ("fan", "temp"):
        data["fault"] = read(node.with_name(channel + "_fault"))
    if raw["status"] == "read":
        if not INTEGER.fullmatch(raw["value"]):
            data["conversion"] = {"status": "invalid_integer"}
        else:
            value = int(raw["value"])
            if kind == "fan" and value < 0:
                data["conversion"] = {"status": "out_of_range"}
            else:
                data["conversion"] = {"status": "converted", "value": value if divisor == 1 else value / divisor,
                                      "unit": unit, "divisor": divisor}
    return data


def hwmon(root):
    nodes, status = directory(root / "class/hwmon")
    chips = []
    for node in nodes:
        if not re.fullmatch(r"hwmon\d+", node.name):
            continue
        entries, enumerated = directory(node)
        name = read(node / "name")
        chip = {"name": name, "hwmon": node.name, "path": link(node), "device": link(node / "device"),
                "driver": link(node / "device/driver"), "attributes": enumerated, "inputs": []}
        if name.get("value") in GPU_CHIPS:
            chip["input_status"] = "gpu_outside_board_scope"
        elif enumerated["status"] != "read":
            chip["input_status"] = "attribute_list_unavailable"
        else:
            for entry in entries:
                match = INPUTS.fullmatch(entry.name)
                if match:
                    chip["inputs"].append(sample(entry, match[1]))
            chip["input_status"] = "inputs_exported" if chip["inputs"] else "no_inputs_exported"
        chips.append(chip)
    return {"directory": status, "chips": chips}


def inventory(root):
    devices = {}
    for bus in ("wmi", "acpi", "pnp", "platform"):
        nodes, status = directory(root / "bus" / bus / "devices")
        selected = nodes
        if bus == "platform":
            selected = [node for node in nodes if node.name.lower().startswith(("it87", "eeepc", "asus", "wmi", "atk"))]
        devices[bus] = {"directory": status, "devices": [binding(node, bus == "pnp") for node in selected]}
    return devices


def board_identity(root):
    board = {field: read(root / "class/dmi/id" / field) for field in ("board_vendor", "board_name", "bios_version")}
    matches = (
        [field.get("value") for field in board.values()]
        == ["ASUSTeK COMPUTER INC.", "ROG STRIX B350-F GAMING", "6203"]
    )
    return board, matches


def capture(phase, root=Path("/sys")):
    board, matches = board_identity(root)
    inputs = hwmon(root)
    available = inputs["directory"]["status"] == "read" or any(field["status"] == "read" for field in board.values())
    data = {"schema_version": 1, "phase": phase, "captured_at": datetime.now(timezone.utc).isoformat(),
            "kernel_release": os.uname().release, "kernel_signature": read(Path("/proc/version_signature")), "board": board,
            "status": "captured" if available else "board_interfaces_unavailable", "qualified_it8665_projection": matches,
            "hwmon": inputs}
    if phase == "inventory":
        data["buses"] = inventory(root)
    return data


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("phase", choices=("inventory", "idle", "load", "recovery"))
    args = parser.parse_args()
    data = capture(args.phase)
    json.dump(data, sys.stdout, ensure_ascii=False, indent=2)
    print()
    return 0 if data["status"] == "captured" else 2


if __name__ == "__main__":
    sys.exit(main())
