/**
 * Parse lyrics text into displayable lines. `.lrc` carries `[mm:ss.xx]` timestamps (possibly several per
 * line, e.g. repeated choruses) and metadata tags ([ar:], [ti:], …) which are dropped. `.txt` is plain.
 * A synced result is sorted by time so the active-line lookup is a simple scan.
 *
 * Ported from the mobile app (packages/core/src/services/lyrics.ts) — same file format, same server,
 * so the two must agree on what a line is.
 */
export type LyricLine = { timeSec?: number; text: string };
export type ParsedLyrics = { synced: boolean; lines: LyricLine[] };

const TIME_RE = /\[(\d{1,2}):(\d{2})(?:[.:](\d{1,3}))?\]/g;
const META_RE = /^\[(ar|ti|al|by|offset|length|re|ve|au|la|id):/i;

/**
 * Lines are treated as synced whenever the text actually contains `[mm:ss]` timestamps — the server's
 * `X-Lyrics-Format` header is not trusted (it need not survive a proxy, and embedded lyrics carrying
 * timestamps should sync regardless of which file they came from). No timestamps → plain text.
 */
export function parseLyrics(text: string): ParsedLyrics {
  if (!/\[\d{1,2}:\d{2}/.test(text)) {
    return { synced: false, lines: text.split(/\r?\n/).map((t) => ({ text: t.trim() })) };
  }

  const out: LyricLine[] = [];
  for (const rawLine of text.split(/\r?\n/)) {
    if (META_RE.test(rawLine.trim())) continue;
    const stamps: number[] = [];
    let m: RegExpExecArray | null;
    TIME_RE.lastIndex = 0;
    while ((m = TIME_RE.exec(rawLine)) !== null) {
      const min = Number(m[1]);
      const sec = Number(m[2]);
      // "[00:12.3]" is three tenths, not three milliseconds — pad right before reading as thousandths.
      const frac = m[3] ? Number(`${m[3]}00`.slice(0, 3)) / 1000 : 0;
      stamps.push(min * 60 + sec + frac);
    }
    const lyric = rawLine.replace(TIME_RE, '').trim();
    if (!stamps.length) {
      if (lyric) out.push({ text: lyric }); // a plain line inside an otherwise-synced file
      continue;
    }
    for (const t of stamps) out.push({ timeSec: t, text: lyric });
  }

  const synced = out.some((l) => l.timeSec != null);
  if (synced) out.sort((a, b) => (a.timeSec ?? 0) - (b.timeSec ?? 0));
  return { synced, lines: out };
}

/**
 * Index of the active line for a playback position (synced only); -1 before the first line. The 0.2s
 * lookahead lands the highlight fractionally early, which reads as on-time — arriving late reads as lag.
 */
export function activeLineIndex(lines: LyricLine[], positionSec: number): number {
  let idx = -1;
  for (let i = 0; i < lines.length; i++) {
    const t = lines[i]?.timeSec;
    if (t == null) continue;
    if (t <= positionSec + 0.2) idx = i;
    else break;
  }
  return idx;
}
