"""Timed transcript segment helpers for video↔speech alignment."""

from __future__ import annotations

import re
from typing import Any


_SENTENCE_SPLIT = re.compile(r"(?<=[.!?])\s+|\n+")


def synthesize_timed_segments(
    text: str,
    *,
    duration_ms: int,
    max_segments: int = 40,
) -> list[dict[str, Any]]:
    """Split plain transcript text into approximate timed segments.

    Used when the STT model returns text but no ``start``/``end`` timestamps
    (e.g. gpt-4o-mini-transcribe). Segments are evenly spaced across
    ``duration_ms`` — good enough for proximity alignment, not word-accurate.
    """
    cleaned = (text or "").strip()
    if not cleaned or duration_ms <= 0:
        return []

    parts = [p.strip() for p in _SENTENCE_SPLIT.split(cleaned) if p and p.strip()]
    if not parts:
        parts = [cleaned]
    if len(parts) > max_segments:
        # Merge into max_segments buckets by character weight
        total = sum(len(p) for p in parts) or 1
        target = total / max_segments
        buckets: list[str] = []
        buf = ""
        for p in parts:
            if buf and len(buf) + len(p) >= target and len(buckets) < max_segments - 1:
                buckets.append(buf.strip())
                buf = p
            else:
                buf = f"{buf} {p}".strip() if buf else p
        if buf:
            buckets.append(buf.strip())
        parts = buckets

    n = len(parts)
    weights = [max(1, len(p)) for p in parts]
    total_w = float(sum(weights))
    segments: list[dict[str, Any]] = []
    cursor = 0.0
    for i, (part, w) in enumerate(zip(parts, weights)):
        span = duration_ms * (w / total_w)
        start = int(round(cursor))
        cursor += span
        end = int(round(cursor)) if i < n - 1 else duration_ms
        if end <= start:
            end = min(duration_ms, start + 1)
        segments.append(
            {
                "start_ms": max(0, start),
                "end_ms": max(start + 1, end),
                "text": part,
                "confidence": None,
                "speaker": None,
            }
        )
    if segments:
        segments[-1]["end_ms"] = max(segments[-1]["end_ms"], duration_ms)
    return segments
