"""TP2 逐段计时（tp2-comfy v1.1.0 起）：只有 TP_PROFILE=1 时才测量，默认零开销。

设计取舍（对照帖主 lcz.me/topic/2693 的做法）：
  * 计算类段落用 torch.cuda.Event 卡时间点，**不在热路径里插 synchronize**，
    避免"插桩本身改变执行时序"（帖主自己承认 profile 跑与普通跑不是同一实验条件）；
  * 归约类（RCCL all_reduce）本身是阻塞调用，额外用 perf_counter 记墙钟，
    这样既有 GPU 时间也有"等对端"的时间；
  * 结果按类别累计（总毫秒 + 调用次数），守护线程每 5 s 覆盖写一次 JSON，
    所以 kill -TERM 也能拿到最后一次快照（atexit 在 SIGTERM 下不执行）。

用法：
  TP_PROFILE=1 TP_PROFILE_OUT=/tmp/rank0.json TP_RANK=0 python tp_boot.py ...
"""
import json
import os
import threading
import time

import torch

ENABLED = os.environ.get("TP_PROFILE", "") not in ("", "0", "false", "False")
OUT = os.environ.get("TP_PROFILE_OUT", "/tmp/tp_prof.json")
RANK = os.environ.get("TP_RANK", "?")

_ev = {}       # cat -> [(ev0, ev1), ...]
_acc = {}      # cat -> [总毫秒, 调用次数]（墙钟类）
_lock = threading.Lock()
_started = {"t": False}
MAXPAIRS = 20000


def _ticker():
    while True:
        time.sleep(5.0)
        try:
            dump()
        except Exception as e:                      # noqa: BLE001 计时不能拖垮生产进程
            print("[tp-prof] dump 失败：%r" % (e,), flush=True)


def _ensure_ticker():
    if not _started["t"]:
        _started["t"] = True
        threading.Thread(target=_ticker, daemon=True, name="tp-prof").start()


def mark():
    """记录一个 GPU 时间点；未启用时返回 None。"""
    if not ENABLED:
        return None
    _ensure_ticker()
    ev = torch.cuda.Event(enable_timing=True)
    ev.record()
    return ev


def add(cat, t0, t1):
    """把一段 Event 区间记到 cat 名下（t0/t1 任一是 None 就跳过）。"""
    if not ENABLED or t0 is None or t1 is None:
        return
    with _lock:
        lst = _ev.setdefault(cat, [])
        lst.append((t0, t1))
        if len(lst) >= MAXPAIRS:
            _fold(cat)


def wall(cat, seconds):
    """记一段墙钟时间（归约等阻塞调用用）。"""
    if not ENABLED:
        return
    with _lock:
        s = _acc.setdefault(cat, [0.0, 0])
        s[0] += seconds * 1000.0
        s[1] += 1


def _fold(cat):
    """把已完成的 Event 对折算成毫秒累计（调用方持锁）。

    不调用 synchronize（后台线程里 sync 会给主线程插一次队列排空，反而污染测量）；
    还没跑完的事件直接留着，等下一次 dump 再折。
    """
    pairs = _ev.get(cat) or []
    if not pairs:
        return
    total = 0.0
    keep = []
    n = 0
    for a, b in pairs:
        try:
            if not (a.query() and b.query()):
                keep.append((a, b))
                continue
            total += a.elapsed_time(b)
            n += 1
        except Exception:                            # noqa: BLE001 事件可能已被回收
            pass
    if n:
        s = _acc.setdefault(cat, [0.0, 0])
        s[0] += total
        s[1] += n
    _ev[cat] = keep


def dump():
    if not ENABLED:
        return
    with _lock:
        for cat in list(_ev.keys()):
            _fold(cat)
        res = {k: [round(v[0], 1), int(v[1])] for k, v in _acc.items()}
    try:
        with open(OUT, "w") as f:
            json.dump({"rank": RANK, "cats_ms_calls": res}, f, indent=1)
    except OSError as e:
        print("[tp-prof] 写 %s 失败：%r" % (OUT, e), flush=True)
    print("[tp-prof] rank%s %s" % (RANK, json.dumps(res, ensure_ascii=False)), flush=True)


def reset():
    with _lock:
        _ev.clear()
        _acc.clear()
