import psutil
import time
import subprocess
import sys


def monitor_with_psutil(pid=None):
    """Monitor CPU usage of a process using psutil library"""
    if pid is None:
        # Monitor self if no PID provided
        process = psutil.Process()
    else:
        process = psutil.Process(pid)

    print(f"Monitoring process {process.pid} ({process.name()})")
    print("Press Ctrl+C to stop monitoring")

    try:
        while True:
            # Get CPU usage as a percentage
            cpu_percent = process.cpu_percent(interval=1)
            memory_info = process.memory_info()
            memory_mb = memory_info.rss / (1024 * 1024)  # Convert to MB

            print(f"CPU: {cpu_percent}% | Memory: {memory_mb:.2f} MB")
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nMonitoring stopped")


def run_script_with_monitoring(script_path):
    """Run a Python script and monitor its CPU usage"""
    # Start the script as a subprocess
    process = subprocess.Popen([sys.executable, script_path])

    try:
        # Monitor the subprocess
        monitor_with_psutil(process.pid)
    except KeyboardInterrupt:
        # Ensure the subprocess is terminated when monitoring stops
        process.terminate()
        print(f"\nTerminated process {process.pid}")


if __name__ == "__main__":
    # If a script path is provided, run and monitor that script
    if len(sys.argv) > 1:
        run_script_with_monitoring(sys.argv[1])
    else:
        print("Usage:")
        print(
            f"1. Run with a script: {sys.executable} {sys.argv[0]} path/to/script.py")
        print(
            f"2. Monitor an existing process: {sys.executable} {sys.argv[0]} --pid PID_NUMBER")

        # Check if --pid argument is provided
        if "--pid" in sys.argv and len(sys.argv) > sys.argv.index("--pid") + 1:
            pid = int(sys.argv[sys.argv.index("--pid") + 1])
            monitor_with_psutil(pid)
