#!/usr/bin/env python3
"""Read clock, thermal and PCIe evidence from the Linux recovery system."""
import argparse
import json
from pathlib import Path
import re
import subprocess

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--sys", type=Path, default=Path("/sys"))
parser.add_argument("--uboot-clock-dump", type=Path, help="Optional captured U-Boot clock output")
args = parser.parse_args()


def contents(path):
    try:
        return path.read_text().strip()
    except OSError:
        return None


def number(path, multiplier=1):
    value = contents(path)
    return int(value) * multiplier if value and re.fullmatch(r"-?\d+", value) else None


cpu = []
for policy in sorted(args.sys.glob("devices/system/cpu/cpufreq/policy*")):
    cpu.append(dict(policy=policy.name, cores=contents(policy / "affected_cpus"),
                    observed_hz=number(policy / "cpuinfo_cur_freq", 1000),
                    policy_hz=number(policy / "scaling_cur_freq", 1000),
                    driver=contents(policy / "scaling_driver")))

thermal = [dict(zone=path.name, kind=contents(path / "type"), millidegrees_c=number(path / "temp"))
           for path in sorted(args.sys.glob("class/thermal/thermal_zone*"))]
ddr = [dict(device=path.name, hz=number(path / "cur_freq"))
       for path in sorted(args.sys.glob("class/devfreq/*"))
       if re.search(r"dmc|ddr", path.name, re.IGNORECASE)]
clocks = {}
summary = contents(args.sys / "kernel/debug/clk/clk_summary")
if summary:
    for line in summary.splitlines():
        match = re.match(r"\s*(armclk|[^ ]*mac[01][^ ]*|clk_ddr[^ ]*)\s+\d+\s+\d+\s+\d+\s+(\d+)", line)
        if match:
            clocks[match[1]] = int(match[2])

pcie = {}
try:
    result = subprocess.run(["lspci", "-Dvv"], capture_output=True, text=True, check=True, timeout=5)
except (OSError, subprocess.SubprocessError):
    pass
else:
    for device in re.split(r"(?=^\S+\s+)", result.stdout, flags=re.MULTILINE):
        if re.search(r"RTL8125|PCI bridge", device):
            first, *rest = device.strip().splitlines()
            pcie[first] = [line.strip() for line in rest
                           if re.search(r"DevCap:|DevCtl:|MaxPayload|LnkSta:|LnkCap:|CESta:|UESta:", line)]

print(json.dumps(dict(source="Linux recovery kernel", cpu=cpu, ddr=ddr, thermal=thermal,
                      clock_tree_hz=clocks, pcie=pcie,
                      uboot_clock_dump=contents(args.uboot_clock_dump) if args.uboot_clock_dump else None), indent=2))
