// JSON (.json) export. Stable, versioned, machine-readable transcript shape.

import type { Segment } from '../types';

/** Serializable transcript envelope. `version` is bumped on breaking changes. */
export interface TranscriptExport {
  version: 1;
  title?: string;
  /** Total duration in seconds = the largest segment end (0 if no segments). */
  durationSec: number;
  segments: Segment[];
}

/**
 * Render segments as pretty-printed (2-space) JSON.
 * `durationSec` is the maximum segment `end` (0 when there are no segments).
 * A `title` is included only when provided and non-empty.
 */
export function toJson(segments: Segment[], opts?: { title?: string }): string {
  let durationSec = 0;
  for (const seg of segments) {
    if (seg.end > durationSec) durationSec = seg.end;
  }
  const title = opts?.title?.trim();
  const payload: TranscriptExport = {
    version: 1,
    ...(title ? { title } : {}),
    durationSec,
    segments,
  };
  return JSON.stringify(payload, null, 2);
}
