// ml-cover.jsx — Cover / sample / interpolation detection
// ────────────────────────────────────────────────────────────────────
// Scans the catalog (and external "found" tracks) for unregistered uses of
// our works:
//
//   01 COVER          full re-recording, same composition, different artist
//   02 SAMPLE         direct audio lift (chops, loops, vocal cut)
//   03 INTERPOLATION  re-played melody/lyric over new beat (no audio lift)
//
// Detection signals (synth, wired to LookEngine + audio fingerprint when present):
//   - Audio fingerprint partial-match (sample lift)
//   - Lyric similarity (interpolation / cover w/ rewrite)
//   - Melody contour overlap (interpolation)
//   - Title fuzzy-match
//   - Credit-string LLM extraction (cover usually credits original writer)
//
// EXPORT: window.CoverEngine
// ────────────────────────────────────────────────────────────────────
(function () {
  if (typeof window === 'undefined') return;

  function rseed(s) {
    s = String(s || 'x'); let h = 0;
    for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
    let a = h ^ 0x9e3779b9, b = h ^ 0xdeadbeef, c = h ^ 0x41c6ce57, d = h ^ 0x6b79f5d3;
    return function () {
      a |= 0; b |= 0; c |= 0; d |= 0;
      const t = (((a + b) | 0) + d) | 0; d = (d + 1) | 0;
      a = b ^ (b >>> 9); b = (c + (c << 3)) | 0; c = (c << 21 | c >>> 11);
      c = (c + t) | 0;
      return (t >>> 0) / 4294967296;
    };
  }

  // Synth a pool of "discovered" tracks that reference our catalog
  function buildDiscoveryPool(opts) {
    opts = opts || {};
    const works = (window.__WORKS || window.WORKS || []).slice(0, opts.limit || 80);
    const out = [];
    const ARTISTS = [
      'Layla Vance','Ofelia Mar','Mira Heath','Soren Vale','Casi Boon','Ella Vance',
      'Toro Mar','LANYA','Pearce James','Reka Pixx','Khaled & The Mode','Velour Skies',
      'Mateus Lo','Junipero','Esme Wave','Kaiokane','April Sade','Rey Polvo',
      'Black Mosque','Lee Yana','PINK CHEMIST','Soner Cay','VYRA','Kingsta','OM RX'
    ];
    const PLATFORMS = ['Spotify','Apple Music','YouTube','SoundCloud','TikTok','Bandcamp'];

    works.forEach(w => {
      const rng = rseed('cov·' + w.id);
      // 0–3 derivative tracks per work
      const n = rng() < 0.45 ? 0 : Math.floor(rng() * 3) + 1;
      for (let i = 0; i < n; i++) {
        const kind = rng() < 0.40 ? 'cover' : rng() < 0.65 ? 'sample' : 'interpolation';
        const artist = ARTISTS[Math.floor(rng() * ARTISTS.length)];
        const platform = PLATFORMS[Math.floor(rng() * PLATFORMS.length)];
        const titleSuffix = kind === 'cover' ? '' : kind === 'sample' ? ' (samples ' + w.title.split(' ').slice(0,2).join(' ') + ')' : '';
        const altTitle = kind === 'cover'
          ? w.title
          : ['Sunset Hymn','Big Lights','New Slang','Grace','First Bloom','Hurt Like That','Heaven Knows','Boa Noite','Cordillera','Vacaciones'][Math.floor(rng() * 10)] + titleSuffix;

        // Confidence factors
        const fpMatch = kind === 'sample' ? 0.55 + rng() * 0.42 : kind === 'cover' ? 0.10 + rng() * 0.20 : 0.05 + rng() * 0.18;
        const lyricSim = kind === 'cover' ? 0.92 + rng() * 0.07 : kind === 'interpolation' ? 0.55 + rng() * 0.35 : 0.10 + rng() * 0.30;
        const melodySim = kind === 'cover' ? 0.88 + rng() * 0.10 : kind === 'interpolation' ? 0.78 + rng() * 0.15 : 0.20 + rng() * 0.35;
        const titleSim  = kind === 'cover' ? 0.95 : kind === 'interpolation' ? 0.20 : 0.05;
        const credited  = rng() > (kind === 'cover' ? 0.62 : kind === 'sample' ? 0.78 : 0.85); // most are uncredited
        const streams   = Math.round(2_000 + rng() * 800_000);
        const ageMonths = Math.floor(1 + rng() * 24);

        // Confidence ensemble
        const detectionScore = Math.round(
          (kind === 'sample' ? fpMatch * 0.6 : 0) +
          (kind === 'cover' ? (lyricSim * 0.4 + melodySim * 0.3 + titleSim * 0.15) : 0) +
          (kind === 'interpolation' ? (lyricSim * 0.3 + melodySim * 0.5) : 0) +
          (kind === 'sample' ? (lyricSim * 0.10 + melodySim * 0.10) : 0)
        ) * 100;
        const detection = Math.min(99, Math.max(35, detectionScore + 10));

        // $ recovery: assume mech rate
        const rate = kind === 'sample' ? 0.0042 : kind === 'cover' ? 0.0056 : 0.0038;
        const recoveryEstimate = streams * rate;

        out.push({
          id: 'COV-' + w.id + '-' + i,
          kind,
          workId: w.id,
          workTitle: w.title,
          discoveredTitle: altTitle,
          discoveredArtist: artist,
          platform,
          streams,
          ageMonths,
          fpMatch: Math.round(fpMatch * 100),
          lyricSim: Math.round(lyricSim * 100),
          melodySim: Math.round(melodySim * 100),
          titleSim: Math.round(titleSim * 100),
          credited,
          detection,
          recoveryEstimate: Math.round(recoveryEstimate * 100) / 100,
          status: credited ? 'monitored' : (detection > 80 ? 'unregistered' : 'flagged'),
          severity: detection > 80 && !credited ? 'high' : detection > 65 ? 'med' : 'low',
        });
      }
    });

    return out.sort((a, b) => b.recoveryEstimate - a.recoveryEstimate);
  }

  function summarize(items) {
    const sum = { total: 0, cover: 0, sample: 0, interp: 0, unregistered: 0, recoveryEstimate: 0 };
    items.forEach(i => {
      sum.total += 1;
      sum[i.kind === 'interpolation' ? 'interp' : i.kind] += 1;
      if (!i.credited) sum.unregistered += 1;
      sum.recoveryEstimate += i.recoveryEstimate || 0;
    });
    sum.recoveryEstimate = Math.round(sum.recoveryEstimate * 100) / 100;
    return sum;
  }

  function forWork(workId) {
    const all = window.__COVER_DISCOVERY || (window.__COVER_DISCOVERY = buildDiscoveryPool());
    return all.filter(c => c.workId === workId);
  }

  window.CoverEngine = { buildDiscoveryPool, summarize, forWork };
  console.log('[CoverEngine] loaded');
})();
