"""Response-format renderers for the OpenAI-compatible transcription endpoint.

Input is the engine's own result shape:
  text: str
  meta: {"duration": float|None, "language": str|None,
         "segments": [{"start": float, "end": float, "text": str}, ...]}

Output mirrors OpenAI /v1/audio/transcriptions response_format values.
"""
from __future__ import annotations

VALID_FORMATS = {"json", "verbose_json", "text", "srt", "vtt"}


def _fmt_timestamp(seconds: float, *, comma: bool) -> str:
    if seconds < 0:
        seconds = 0.0
    ms = int(round(seconds * 1000))
    h, ms = divmod(ms, 3_600_000)
    m, ms = divmod(ms, 60_000)
    s, ms = divmod(ms, 1000)
    sep = "," if comma else "."
    return f"{h:02d}:{m:02d}:{s:02d}{sep}{ms:03d}"


def render(text: str, meta: dict, response_format: str) -> tuple[str, str]:
    """Return (body, media_type) for the requested format."""
    fmt = response_format if response_format in VALID_FORMATS else "json"
    segments = meta.get("segments") or []

    if fmt == "text":
        return text, "text/plain; charset=utf-8"

    if fmt == "srt":
        return _render_srt(segments), "text/plain; charset=utf-8"

    if fmt == "vtt":
        return _render_vtt(segments), "text/plain; charset=utf-8"

    if fmt == "verbose_json":
        import json
        body = {
            "task": "transcribe",
            "language": meta.get("language"),
            "duration": meta.get("duration"),
            "text": text,
            "segments": [
                {
                    "id": i,
                    "start": round(float(s.get("start", 0.0)), 3),
                    "end": round(float(s.get("end", 0.0)), 3),
                    "text": s.get("text", ""),
                }
                for i, s in enumerate(segments)
            ],
        }
        return json.dumps(body, ensure_ascii=False), "application/json"

    # default: minimal json
    import json
    return json.dumps({"text": text}, ensure_ascii=False), "application/json"


def _render_srt(segments: list[dict]) -> str:
    lines: list[str] = []
    for i, s in enumerate(segments, start=1):
        start = _fmt_timestamp(float(s.get("start", 0.0)), comma=True)
        end = _fmt_timestamp(float(s.get("end", 0.0)), comma=True)
        lines.append(str(i))
        lines.append(f"{start} --> {end}")
        lines.append((s.get("text", "") or "").strip())
        lines.append("")
    return "\n".join(lines)


def _render_vtt(segments: list[dict]) -> str:
    lines: list[str] = ["WEBVTT", ""]
    for s in segments:
        start = _fmt_timestamp(float(s.get("start", 0.0)), comma=False)
        end = _fmt_timestamp(float(s.get("end", 0.0)), comma=False)
        lines.append(f"{start} --> {end}")
        lines.append((s.get("text", "") or "").strip())
        lines.append("")
    return "\n".join(lines)
