import axios from 'axios';

export interface SubtitleCue {
  start: number; // seconds
  end: number; // seconds
  text: string; // may contain line breaks
}

/** Parse "00:01:23,456" (SRT) or "00:01:23.456" (VTT) to seconds. */
function parseTimestamp(ts: string): number {
  const normalized = ts.replace(',', '.').trim();
  const parts = normalized.split(':');
  if (parts.length === 3) {
    return (
      parseFloat(parts[0]) * 3600 +
      parseFloat(parts[1]) * 60 +
      parseFloat(parts[2])
    );
  }
  if (parts.length === 2) {
    return parseFloat(parts[0]) * 60 + parseFloat(parts[1]);
  }
  return parseFloat(normalized);
}

function stripTags(text: string): string {
  return text.replace(/<[^>]+>/g, '');
}

function parseSRT(content: string): SubtitleCue[] {
  const cues: SubtitleCue[] = [];
  const blocks = content
    .trim()
    .replace(/\r\n/g, '\n')
    .split(/\n\n+/);

  for (const block of blocks) {
    const lines = block.split('\n');
    const timeLineIdx = lines.findIndex(l => l.includes('-->'));
    if (timeLineIdx === -1) continue;

    const timeParts = lines[timeLineIdx].split('-->');
    if (timeParts.length !== 2) continue;

    const start = parseTimestamp(timeParts[0]);
    const end = parseTimestamp(timeParts[1]);
    const text = stripTags(
      lines
        .slice(timeLineIdx + 1)
        .join('\n')
        .trim(),
    );

    if (text && !isNaN(start) && !isNaN(end)) {
      cues.push({start, end, text});
    }
  }

  return cues;
}

function parseVTT(content: string): SubtitleCue[] {
  let cleaned = content.trim().replace(/\r\n/g, '\n');
  // Remove WEBVTT header
  if (cleaned.startsWith('WEBVTT')) {
    const headerEnd = cleaned.indexOf('\n\n');
    if (headerEnd !== -1) {
      cleaned = cleaned.slice(headerEnd + 2);
    }
  }
  // Remove STYLE and NOTE blocks
  cleaned = cleaned.replace(/^(STYLE|NOTE)\n[\s\S]*?\n\n/gm, '');
  return parseSRT(cleaned);
}

export function parseSubtitles(content: string, url: string): SubtitleCue[] {
  if (
    url.includes('.vtt') ||
    url.includes('vtt') ||
    content.trimStart().startsWith('WEBVTT')
  ) {
    return parseVTT(content);
  }
  return parseSRT(content);
}

export async function fetchAndParseSubtitles(
  url: string,
): Promise<SubtitleCue[]> {
  const response = await axios.get(url, {
    timeout: 10000,
    responseType: 'text',
  });
  return parseSubtitles(response.data, url);
}

/** Find the active cue at a given time. Returns text or null. */
export function findActiveCue(
  cues: SubtitleCue[],
  time: number,
): string | null {
  for (const cue of cues) {
    if (time >= cue.start && time <= cue.end) {
      return cue.text;
    }
    if (cue.start > time + 1) break;
  }
  return null;
}
