#!/usr/bin/env python3
"""Grafica cwnd en el tiempo a partir de los CSV que deja bench.py flow --csv.

    python3 plot_cwnd.py cwnd.png reno.csv cubic.csv
"""
import csv
import os
import sys

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402


def read_rows(path):
    with open(path, encoding="utf-8") as file:
        return list(csv.DictReader(file))


def main():
    if len(sys.argv) < 3:
        print(__doc__)
        return 1
    target, *sources = sys.argv[1:]
    figure, (top, bottom) = plt.subplots(2, 1, sharex=True, figsize=(9, 5.5))
    for source in sources:
        rows = read_rows(source)
        if not rows:
            print(f"{source}: no tiene muestras", file=sys.stderr)
            return 1
        times = [float(row["t_s"]) for row in rows]
        label = os.path.splitext(os.path.basename(source))[0]
        top.plot(times, [int(row["cwnd_segments"]) for row in rows], label=label)
        bottom.plot(times, [float(row["rtt_ms"]) for row in rows], label=label)
    top.set_ylabel("cwnd (segmentos)")
    bottom.set_ylabel("RTT suavizado (ms)")
    bottom.set_xlabel("tiempo (s)")
    top.legend()
    figure.tight_layout()
    figure.savefig(target, dpi=150)
    print(f"gráfico en {target}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
