import { TracklistEntry } from '../types'

export const parseTracklist = (lines: string[]): TracklistEntry[] => {
  return lines.map((line) => {
    const trimmed = line.trim()
    // Try to parse as "%ts %tn - %an"
    const match = trimmed.match(/^(\d{1,2}:\d{2}(:\d{2})?)\s+(.+?)\s*-\s*(.+)$/)
    if (match) {
      return {
        ts: match[1],
        tn: match[3].trim(),
        an: match[4].trim(),
      }
    }
    // Try to parse as "%ts %tn"
    const simpleMatch = trimmed.match(/^(\d{1,2}:\d{2}(:\d{2})?)\s+(.+)$/)
    if (simpleMatch) {
      return {
        ts: simpleMatch[1],
        tn: simpleMatch[3].trim(),
      }
    }
    // Fallback: just use the line as is (will be flagged as error)
    return {
      ts: '',
      tn: trimmed,
    }
  })
}

export const validateTracklist = (
  entries: TracklistEntry[]
): { isValid: boolean; errors: { line: number; message: string }[] } => {
  const errors: { line: number; message: string }[] = []

  entries.forEach((entry, index) => {
    const lineNum = index + 1
    if (!entry.ts || !entry.ts.trim()) {
      errors.push({ line: lineNum, message: 'Missing timestamp (%ts)' })
    } else {
      // Validate timestamp format
      const ts = entry.ts.trim()
      if (!/^\d{1,2}:\d{2}(:\d{2})?$/.test(ts) && !/^\d{1,2}:\d{2}-\d{1,2}:\d{2}$/.test(ts)) {
        errors.push({ line: lineNum, message: 'Invalid timestamp format. Expected mm:ss or mm:ss-HH:MM:SS' })
      }
    }
    if (!entry.tn || !entry.tn.trim()) {
      errors.push({ line: lineNum, message: 'Missing track name (%tn)' })
    }
  })

  return {
    isValid: errors.length === 0,
    errors,
  }
}