import os

def plot_resources(data, output_dir: str = '.'):
    if not data:
        print("No resource data to plot.")
        return

    try:
        import matplotlib.pyplot as plt
        import numpy as np

        # Normalize time to start from 0
        times = [d['time'] for d in data]
        t0 = times[0]
        time_rel = [t - t0 for t in times]
        cpu_usage = [d['cpu_usage'] for d in data]
        memory_usage = [d['memory_usage'] for d in data]

        # Plot CPU Usage
        plt.figure(figsize=(10, 5))
        plt.plot(time_rel, cpu_usage, label='CPU Usage (%)', color='blue')
        plt.xlabel('Time (s)')
        plt.ylabel('Usage (%)')
        plt.title('CPU Usage over Time')
        plt.grid(True)
        plt.legend()
        plt.savefig(os.path.join(output_dir, 'cpu_usage.png'))
        plt.close()

        # Plot Memory Usage
        plt.figure(figsize=(10, 5))
        plt.plot(time_rel, memory_usage, label='Memory Usage (%)', color='green')
        plt.xlabel('Time (s)')
        plt.ylabel('Usage (%)')
        plt.title('Memory Usage over Time')
        plt.grid(True)
        plt.legend()
        plt.savefig(os.path.join(output_dir, 'memory_usage.png'))
        plt.close()
        
        print(f"Plots saved to {output_dir}")
    except ImportError:
        print("matplotlib not found. Skipping plot generation.")
    except Exception as e:
        print(f"Failed to generate plots: {e}")
