import time
import os

RAPL_PATH = "/sys/class/powercap/intel-rapl:0/energy_uj" 
INTERVAL_SEC = 1.0  # configurable via command-line argument or env var

def read_energy(path):
    try:
        with open(path, "r") as f:
            return int(f.read().strip())
    except FileNotFoundError:
        raise RuntimeError(f"RAPL support not available: {path}")

def calculate_power(energy_before, energy_after, interval_sec):
    delta_uj = energy_after - energy_before
    power_watts = (delta_uj / 1_000_000) / interval_sec
    return f"{power_watts:.2f} Watts"

if __name__ == "__main__":
    if os.geteuid() != 0:
        print("Please run this script as root.")
        exit(1)
    
    try:
        # RAPL support check
        with open(RAPL_PATH, "r") as f:
            _ = int(f.read().strip())
        
        while True:
            energy_before = read_energy(RAPL_PATH)
            time.sleep(INTERVAL_SEC)
            energy_after = read_energy(RAPL_PATH)
            
            power_reading = calculate_power(energy_before, energy_after, INTERVAL_SEC)
            print(f"Power Usage: {power_reading}")
    
    except KeyboardInterrupt:
        print("\nStopped.")