// SRT subtitle parser — tolerant of basic formatting and BOM.

import type { SubtitleCue } from '@/types';

const SRT_TIME_REGEX = /(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})/;

function parseTime(s: string): number {
  const m = s.match(SRT_TIME_REGEX);
  if (!m) return 0;
  const h = parseInt(m[1], 10);
  const min = parseInt(m[2], 10);
  const sec = parseInt(m[3], 10);
  const ms = parseInt(m[4].padEnd(3, '0').slice(0, 3), 10);
  return h * 3600 + min * 60 + sec + ms / 1000;
}

export function parseSrt(text: string): SubtitleCue[] {
  // Strip BOM, normalise line endings
  const cleaned = text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
  const blocks = cleaned.split(/\n\s*\n/);
  const cues: SubtitleCue[] = [];
  let id = 1;
  for (const block of blocks) {
    const lines = block.split('\n').map((l) => l.trim()).filter(Boolean);
    if (lines.length < 2) continue;
    // First line may be an index or a timestamp
    let timeLineIdx = 0;
    if (/^\d+$/.test(lines[0]) && lines[1]?.includes('-->')) timeLineIdx = 1;
    const timeLine = lines[timeLineIdx];
    if (!timeLine?.includes('-->')) continue;
    const [fromStr, toStr] = timeLine.split('-->').map((s) => s.trim());
    const text = lines.slice(timeLineIdx + 1).join('\n');
    cues.push({
      id: id++,
      start: parseTime(fromStr),
      end: parseTime(toStr),
      text,
    });
  }
  return cues;
}

export function formatTime(seconds: number): string {
  if (!isFinite(seconds) || seconds < 0) seconds = 0;
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = Math.floor(seconds % 60);
  const ms = Math.floor((seconds - Math.floor(seconds)) * 1000);
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s
    .toString()
    .padStart(2, '0')}.${ms.toString().padStart(3, '0')}`;
}

export function formatTimeShort(seconds: number): string {
  if (!isFinite(seconds) || seconds < 0) seconds = 0;
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
}