"""图文直播条目聚合。

把 ASR 的 segment（一句话级）聚合成"可读、可发布、可回放"的直播条目：
- 段间停顿 > POST_MAX_GAP 秒 → 视为一个自然停顿，切新条目
- 单条超过 POST_MAX_DURATION 秒 → 强制切新条目
每条 post 记录起止时间与 segment 引用，作为回放锚点。
"""

_PUNCT = "。！？；…!?.;"


def _ensure_punct(text):
    """确保句子以标点结尾，避免拼接后粘连。"""
    if text and text[-1] not in _PUNCT:
        return text + "。"
    return text


def build_posts(segments, max_gap=3.0, max_duration=60.0):
    posts = []
    cur = None

    def _flush():
        if cur is None:
            return
        posts.append({
            "start": cur["start"],
            "end": cur["end"],
            "seg_ids": list(cur["seg_ids"]),
            "body": "".join(_ensure_punct(t) for t in cur["texts"]),
            "seg_count": len(cur["seg_ids"]),
        })

    for seg in segments:
        if cur is None:
            cur = {"start": seg["start"], "end": seg["end"],
                   "seg_ids": [], "texts": []}
        elif (seg["start"] - cur["end"] > max_gap) or \
             (seg["end"] - cur["start"] > max_duration):
            _flush()
            cur = {"start": seg["start"], "end": seg["end"],
                   "seg_ids": [], "texts": []}

        cur["seg_ids"].append(seg["id"])
        cur["texts"].append(seg["text"])
        cur["end"] = seg["end"]

    _flush()

    for i, p in enumerate(posts, 1):
        p["id"] = f"post_{i:04d}"
        p["status"] = "draft"          # draft → editing → published → pinned
        p["start"] = round(p["start"], 3)
        p["end"] = round(p["end"], 3)

    return posts
