#!/usr/bin/env python3

import subprocess
import time
import re
import sys
import platform
from datetime import datetime


# Intervalle entre deux mesures, en secondes
INTERVAL = 1
# Fichier de sortie
LOG_FILE = "memory.log"
# Executable Herezh
exe_hz = "HZppfast_Vn-1"



COMMAND = [exe_hz, "-f", "test.info"]


def get_memory_kb(pid):
    """Retourne la memoire RSS du processus en Ko."""

    system = platform.system()

    # -------------------------
    # Linux
    # -------------------------
    if system == "Linux":
        try:
            with open(f"/proc/{pid}/status", "r") as f:
                for line in f:
                    if line.startswith("VmRSS:"):
                        match = re.search(r"(\d+)", line)
                        if match:
                            return int(match.group(1))
        except FileNotFoundError:
            pass

    # -------------------------
    # macOS / Darwin
    # -------------------------
    elif system == "Darwin":
        try:
            result = subprocess.run(
                ["ps", "-o", "rss=", "-p", str(pid)],
                capture_output=True,
                text=True,
                check=True
            )

            output = result.stdout.strip()

            if output:
                return int(output)

        except (subprocess.SubprocessError, ValueError):
            pass

    return None


def main():
    print(f"Lancement de : {' '.join(COMMAND)}")

    process = subprocess.Popen(COMMAND)

    print(f"PID : {process.pid}")

    start_time = time.perf_counter()

    with open(LOG_FILE, "w") as log:
        log.write("#temps(s)    memoire(kb)\n")

        try:
            while process.poll() is None:
                elapsed = time.perf_counter() - start_time
                memory_kb = get_memory_kb(process.pid)

                if memory_kb is not None:
                    print(f"{elapsed}s : {memory_kb} Ko")
                    log.write(f"{elapsed:.3f}          {memory_kb}\n")
                    log.flush()

                time.sleep(INTERVAL)

        except KeyboardInterrupt:
            print("\nArret demande.")

        finally:
            # Attend que le processus se termine s il est encore actif
            if process.poll() is None:
                print("Arret du processus...")
                process.terminate()

            process.wait()


    print(f"\n\nFichier cree : {LOG_FILE}\n")


if __name__ == "__main__":
    main()
