"""
markdown_format - Pure formatting helpers that wrap a transcription result
into a Markdown document.  Kept side-effect free so it is trivially testable.
"""
from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timezone


@dataclass(frozen=True)
class TranscriptSegment:
    """A single timestamped transcript segment."""
    start: float
    end: float
    text: str


def _format_timestamp(seconds: float) -> str:
    """Format seconds as H:MM:SS (or M:SS for short clips)."""
    seconds = max(0, int(seconds))
    h, rem = divmod(seconds, 3600)
    m, s = divmod(rem, 60)
    if h > 0:
        return f"{h}:{m:02d}:{s:02d}"
    return f"{m}:{s:02d}"


def _format_duration(seconds: float) -> str:
    """Human-readable duration like '3:07'."""
    return _format_timestamp(seconds)


def build_transcript_markdown(
    *,
    source_name: str,
    text: str,
    duration: float | None = None,
    language: str | None = None,
    created_at: datetime | None = None,
    segments: list[TranscriptSegment] | None = None,
) -> str:
    """Wrap a raw transcript into a Markdown document with a metadata table.

    When ``segments`` is provided, a timestamped transcript is rendered;
    otherwise the plain joined ``text`` is used.
    """
    created = created_at or datetime.now(timezone.utc).astimezone()
    title = source_name.rsplit(".", 1)[0] if "." in source_name else source_name

    lines: list[str] = [f"# {title}", ""]

    # Deliberately no engine/model/device details here — the output document
    # is user-facing and must not leak implementation internals.
    meta: list[tuple[str, str]] = [("Source", source_name)]
    if duration is not None:
        meta.append(("Duration", _format_duration(duration)))
    if language:
        meta.append(("Language", language))
    meta.append(("Transcribed", created.strftime("%Y-%m-%d %H:%M")))

    lines.append("| Field | Value |")
    lines.append("| --- | --- |")
    for key, value in meta:
        lines.append(f"| {key} | {value} |")
    lines.append("")

    if segments:
        lines.append("## Transcript")
        lines.append("")
        for seg in segments:
            stamp = _format_timestamp(seg.start)
            body = seg.text.strip()
            if body:
                lines.append(f"**[{stamp}]** {body}")
                lines.append("")
    else:
        body = text.strip()
        lines.append(body if body else "_No speech detected._")
        lines.append("")

    return "\n".join(lines).rstrip() + "\n"
