const SEARCH_URL = 'https://itunes.apple.com/search';

// Normalize strings before comparing: lowercase, strip parenthetical/bracket
// suffixes like "(feat. X)" or "- Remastered 2011", strip punctuation.
function normalize(str = '') {
  return str
    .toLowerCase()
    .replace(/\(.*?\)|\[.*?\]/g, ' ')
    .replace(/feat\.?.*$/i, ' ')
    .replace(/[^a-z0-9\s]/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();
}

// Token-overlap similarity: proportion of shared words between two strings,
// weighted so both title and artist must line up for a high score.
function similarity(a, b) {
  const tokensA = new Set(normalize(a).split(' ').filter(Boolean));
  const tokensB = new Set(normalize(b).split(' ').filter(Boolean));
  if (tokensA.size === 0 || tokensB.size === 0) return 0;

  let shared = 0;
  for (const t of tokensA) if (tokensB.has(t)) shared += 1;

  return shared / Math.max(tokensA.size, tokensB.size);
}

function scoreCandidate(candidate, title, artist) {
  const titleScore = similarity(candidate.trackName || '', title);
  const artistScore = similarity(candidate.artistName || '', artist);
  // Artist match matters slightly more than title — avoids matching covers.
  return Math.round((titleScore * 0.45 + artistScore * 0.55) * 100);
}

/**
 * Searches the iTunes/Apple Music catalog for the given title + artist and
 * returns the closest match, or null if nothing crosses the confidence floor.
 */
export async function findAppleMusicMatch(title, artist) {
  const term = encodeURIComponent(`${title} ${artist}`);
  const url = `${SEARCH_URL}?term=${term}&media=music&entity=song&limit=10`;

  const res = await fetch(url);
  if (!res.ok) {
    // Non-fatal by design — Apple Music match is best-effort.
    return null;
  }

  const data = await res.json();
  const results = data.results || [];
  if (results.length === 0) return null;

  const scored = results
    .map((r) => ({ candidate: r, score: scoreCandidate(r, title, artist) }))
    .sort((a, b) => b.score - a.score);

  const best = scored[0];

  const CONFIDENCE_FLOOR = 55;
  if (!best || best.score < CONFIDENCE_FLOOR) {
    return null;
  }

  return {
    apple_music_url: best.candidate.trackViewUrl,
    apple_match_score: best.score,
  };
}
