#!/usr/bin/python3

import argparse
import time
import sys
import os

hostname = "shuttle"
measurement_interval = 5


def get_cpu_frequencies():
    frequencies = []
    try:
        cpu_dirs = [
            d
            for d in os.listdir("/sys/devices/system/cpu/")
            if d.startswith("cpu") and d[3:].isdigit()
        ]
        for cpu_dir in cpu_dirs:
            with open(
                f"/sys/devices/system/cpu/{cpu_dir}/cpufreq/scaling_cur_freq", "r"
            ) as f:
                frequency = int(f.read().strip()) / 1000  # Convert Hz to MHz
                frequencies.append((int(cpu_dir[3:]), frequency))
    except Exception as e:
        print("Error:", e)
    return frequencies


def main():
    parser = argparse.ArgumentParser(description="Query CPU frequencies.")
    parser.add_argument(
        "-s",
        "--human-readable",
        action="store_true",
        help="Print frequencies in human-readable format",
    )
    args = parser.parse_args()

    if args.human_readable:
        frequencies = get_cpu_frequencies()
        for cpu, frequency in frequencies:
            print(f"CPU{cpu} Frequency: {frequency:.2f} MHz")
    else:
        while True:
            frequencies = get_cpu_frequencies()
            timestamp = int(time.time())
            for cpu, frequency in frequencies:
                print(
                    f"PUTVAL {hostname}/cpu-frequency/gauge-cpu{cpu} {timestamp}:{frequency:.0f}"
                )
            sys.stdout.flush()
            time.sleep(measurement_interval)


if __name__ == "__main__":
    main()
