/**
 * Parse chord sheet from plain text
 * Detects chords above lyrics and section headers
 */
export function parseChordSheet(text) {
  const lines = text.split("\n");
  const result = {
    title: "",
    artist: "",
    key: "",
    sections: [],
    chords: new Set(),
    lyrics: "",
  };

  let currentSection = { type: "", lines: [] };
  let lyricsLines = [];

  // Common section headers
  const sectionPattern =
    /^\s*[\[\(]?(verse|chorus|bridge|pre-?chorus|intro|outro|interlude|hook|tag|ending|v\d|c\d|ch\d)[\d\s]*[\]\)]?\s*:?\s*$/i;

  // Chord pattern - detects chords on a line
  const chordLinePattern = /^[\s\w#b/]+$/;
  const chordPattern = /([A-G][#b]?(?:m|maj|min|dim|aug|sus|add)?[0-9]*)/g;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmed = line.trim();

    // Skip empty lines
    if (!trimmed) {
      lyricsLines.push("");
      continue;
    }

    // Check for section headers
    if (sectionPattern.test(trimmed)) {
      if (currentSection.lines.length > 0) {
        result.sections.push({ ...currentSection });
      }
      currentSection = {
        type: trimmed.replace(/[\[\]\(\):]/g, "").trim(),
        lines: [],
      };
      lyricsLines.push(trimmed);
      continue;
    }

    // Check if line contains only chords
    const nextLine = i + 1 < lines.length ? lines[i + 1] : "";
    const isChordLine =
      chordLinePattern.test(trimmed) &&
      trimmed.match(chordPattern) &&
      nextLine.trim() &&
      !chordLinePattern.test(nextLine.trim());

    if (isChordLine) {
      // Extract chords from this line
      const chords = trimmed.match(chordPattern);
      if (chords) {
        chords.forEach((chord) => result.chords.add(chord));
      }

      // Map chords to positions in the next line
      const lyricLine = nextLine;
      let chordedLine = "";
      let lastPos = 0;

      // Find chord positions
      const chordPositions = [];
      let tempLine = trimmed;
      let pos = 0;

      for (const chord of trimmed.split(/\s+/).filter((c) => c.trim())) {
        const chordMatch = chord.match(chordPattern);
        if (chordMatch) {
          const chordPos = trimmed.indexOf(chord, pos);
          chordPositions.push({ chord, position: chordPos });
          pos = chordPos + chord.length;
        }
      }

      // Build lyrics with embedded chords
      chordPositions.forEach((item, idx) => {
        const { chord, position } = item;
        const nextPos = chordPositions[idx + 1]?.position || lyricLine.length;
        const lyricPart = lyricLine.substring(position, nextPos).trim();

        if (lyricPart) {
          chordedLine += `[${chord}]${lyricPart} `;
        }
      });

      lyricsLines.push(chordedLine.trim() || `[${chords[0]}]`);
      currentSection.lines.push(chordedLine.trim());

      // Skip the next line since we processed it
      i++;
      continue;
    }

    // Regular lyric line
    lyricsLines.push(line);
    currentSection.lines.push(line);
  }

  if (currentSection.lines.length > 0) {
    result.sections.push(currentSection);
  }

  result.lyrics = lyricsLines.join("\n");
  result.chords = Array.from(result.chords).join(" ");

  // Try to detect key from first chord
  if (result.chords) {
    const firstChord = result.chords.split(" ")[0];
    result.key = firstChord;
  }

  return result;
}

/**
 * Parse Word document (.docx) using mammoth
 */
export async function parseWordDocument(file) {
  // For now, read as text and parse
  const text = await file.text();
  return parseChordSheet(text);
}

/**
 * Parse PDF document
 */
export async function parsePDFDocument(file) {
  // For now, read as text and parse
  const text = await file.text();
  return parseChordSheet(text);
}

/**
 * Auto-detect file type and parse
 */
export async function parseDocument(file) {
  const fileType = file.type;
  const fileName = file.name.toLowerCase();

  if (fileType === "application/pdf" || fileName.endsWith(".pdf")) {
    return parsePDFDocument(file);
  } else if (
    fileType ===
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
    fileName.endsWith(".docx")
  ) {
    return parseWordDocument(file);
  } else if (fileType === "text/plain" || fileName.endsWith(".txt")) {
    const text = await file.text();
    return parseChordSheet(text);
  } else {
    throw new Error(
      "Unsupported file type. Please upload PDF, Word, or TXT files.",
    );
  }
}
