import os
import subprocess

import matplotlib.pyplot as plt


def run_test(n, threads, threshold):
    cmd = f"./lab2 {n} {threads} {threshold}"
    process = subprocess.Popen(
        cmd.split(), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True
    )
    _, err = process.communicate()
    for line in err.split("\n"):
        if "STAT:" in line:
            return float(line.split("time=")[1])
    return 0


def build_benchmark():
    n_size = 500000
    threshold = 10000
    thread_counts = [0, 1, 2, 4, 8, 12, 16]
    times = []

    print(f"Запуск бенчмарка (N={n_size}, Порог={threshold})...")
    for t in thread_counts:
        t_exec = run_test(n_size, t, threshold)
        times.append(t_exec)
        print(f"Потоков: {t} | Время: {t_exec:.4f}с")

    plt.figure(figsize=(12, 5))

    plt.subplot(1, 2, 1)
    plt.plot(thread_counts, times, "o-", color="blue", label="Фактическое время")
    plt.xlabel("Потоки")
    plt.ylabel("Время (сек)")
    plt.title("Время выполнения")
    plt.grid(True)

    plt.subplot(1, 2, 2)
    t_seq = times[0]
    speedup = [t_seq / x if x > 0 else 1 for x in times]
    plt.plot(thread_counts, speedup, "s-", color="green", label="Ускорение")
    plt.plot(
        thread_counts,
        [x if x > 0 else 1 for x in thread_counts],
        "--",
        color="red",
        alpha=0.5,
    )
    plt.xlabel("Потоки")
    plt.ylabel("Ускорение S")
    plt.title("Масштабируемость")
    plt.grid(True)

    plt.tight_layout()
    plt.savefig("out/performance_results.png")


if __name__ == "__main__":
    if not os.path.exists("out"):
        os.makedirs("out")
    build_benchmark()
