import os
import re
import sys
from collections import defaultdict

import matplotlib

try:
    matplotlib.use("Agg")
except Exception:
    pass
import matplotlib.pyplot as plt

if len(sys.argv) < 2:
    print("Использование: python exporter.py <logfile> <output_dir>")
    sys.exit(1)

logfile = sys.argv[1]
out_dir = sys.argv[2]
os.makedirs(out_dir, exist_ok=True)

base_name = os.path.splitext(os.path.basename(logfile))[0]

pattern = re.compile(r"(START|END).*TID=(\d+).*range=\[(\d+),(\d+)\].*time=([\d.]+)")
events = defaultdict(dict)

with open(logfile) as f:
    for line in f:
        m = pattern.search(line)
        if m:
            typ, tid, l, r, t = m.groups()
            key = (tid, int(l), int(r))
            events[key][typ] = float(t)

rows = []
for (tid, l, r), v in events.items():
    if "START" in v and "END" in v:
        rows.append(
            {
                "tid": tid,
                "start": v["START"],
                "end": v["END"],
                "duration": v["END"] - v["START"],
            }
        )

if not rows:
    sys.exit(1)

rows.sort(key=lambda x: x["start"])
t0 = rows[0]["start"]
for r in rows:
    r["offset"] = r["start"] - t0

unique_tids = sorted(set(r["tid"] for r in rows))
color_map = {tid: plt.cm.tab20(i % 20) for i, tid in enumerate(unique_tids)}

plt.figure(figsize=(12, 6))
for i, r in enumerate(rows):
    plt.plot(
        [r["offset"], r["offset"] + r["duration"]],
        [i, i],
        color=color_map[r["tid"]],
        linewidth=4,
    )

plt.xlabel("Время (сек. от начала)")
plt.ylabel("Задачи (рекурсивные вызовы)")
plt.title(f"Временная диаграмма: {base_name}")
plt.grid(True)
plt.tight_layout()
plt.savefig(os.path.join(out_dir, f"{base_name}.png"))
