import json
import matplotlib.pyplot as plt
from datetime import datetime

# Load the log data from the JSON file
def load_log_data(file_path):
    with open(file_path, 'r') as file:
        data = file.read()
        # Remove the trailing comma if it's present
        if data.endswith(",\n"):
            data = data[:-2]
        return json.loads(f"[{data}]")

# Extract data from the log entries
def extract_data(log_data):
    timestamps = []
    power_data = []
    fan_data = {}
    temperature_data = {}

    for entry in log_data:
        timestamp = datetime.fromisoformat(entry["timestamp"])
        timestamps.append(timestamp)
        
        # Power
        power_data.append(entry["data"]["power"]["PowerConsumedWatts"])
        
        # Fans
        for fan in entry["data"]["fans"]:
            fan_name = fan["FanName"]
            if fan_name not in fan_data:
                fan_data[fan_name] = []
            fan_data[fan_name].append(fan["ReadingRPM"])
        
        # Temperatures
        for temp in entry["data"]["temperatures"]:
            sensor_name = temp["SensorName"]
            if sensor_name not in temperature_data:
                temperature_data[sensor_name] = []
            temperature_data[sensor_name].append(temp["ReadingCelsius"])

    return timestamps, power_data, fan_data, temperature_data

# Plot data
def plot_data(timestamps, power_data, fan_data, temperature_data):
    # Plot power consumption
    plt.figure(figsize=(10, 6))
    plt.plot(timestamps, power_data, label='Power Consumption (Watts)')
    plt.xlabel('Time')
    plt.ylabel('Watts')
    plt.title('Power Consumption Over Time')
    plt.legend()
    plt.grid(True)
    plt.show()
    
    # Plot fan speeds
    plt.figure(figsize=(10, 6))
    for fan_name, readings in fan_data.items():
        plt.plot(timestamps, readings, label=fan_name)
    plt.xlabel('Time')
    plt.ylabel('RPM')
    plt.title('Fan Speeds Over Time')
    plt.legend()
    plt.grid(True)
    plt.show()

    # Plot temperatures
    plt.figure(figsize=(10, 6))
    for sensor_name, readings in temperature_data.items():
        plt.plot(timestamps, readings, label=sensor_name)
    plt.xlabel('Time')
    plt.ylabel('Temperature (Celsius)')
    plt.title('Temperatures Over Time')
    plt.legend()
    plt.grid(True)
    plt.show()

# Main function
def main():
    log_file_path = 'ilo5_log.json'
    log_data = load_log_data(log_file_path)
    timestamps, power_data, fan_data, temperature_data = extract_data(log_data)
    plot_data(timestamps, power_data, fan_data, temperature_data)

if __name__ == "__main__":
    main()

