<?php
require_once 'config.php';

function cleanString($s) {
    return trim(preg_replace('/\s+/', ' ', strtolower($s)));
}

function queryAudioDB($artist, $title) {
    $url = "https://theaudiodb.com/api/v1/json/2/searchtrack.php?s=" . urlencode($artist) . "&t=" . urlencode($title);
    $json = file_get_contents($url);
    $data = json_decode($json, true);
    return $data['track'][0] ?? null;
}

function queryMusicBrainzTags($artist, $title) {
    $query = urlencode("$artist $title");
    $url = "https://musicbrainz.org/ws/2/recording?query=$query&fmt=json&limit=1";
    $json = file_get_contents($url);
    $data = json_decode($json, true);
    $tags = $data['recordings'][0]['tags'] ?? [];
    return array_map(fn($t) => $t['name'], $tags);
}

function getKaggleFeatures($artist, $title) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM audio_features WHERE artist_name = :artist AND track_name = :title LIMIT 1");
    $stmt->execute([':artist' => $artist, ':title' => $title]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function saveTrack(array $track, string $access_token): void {
    global $pdo;

    $title  = $track['name'];
    $artist = implode(', ', array_map(fn($a) => $a['name'], $track['artists']));
    $album  = $track['album']['name'] ?? null;
    $id     = $track['id'];
    $duration = isset($track['duration_ms']) ? round($track['duration_ms'] / 1000) : null;
    $popularity = $track['popularity'];

    // 1. Try Kaggle
    $features = getKaggleFeatures($artist, $title);
    $bpm = $features['bpm'] ?? null;
    $key = $features['key_raw'] ?? null;
    $camelot = $features['camelot'] ?? null;
    $energy = $features['energy'] ?? null;
    $danceability = $features['danceability'] ?? null;

    // 2. Try AudioDB if no Camelot
    $genre = $style = $mood = $theme = null;
    if (!$features || !$camelot) {
        $audiodb = queryAudioDB($artist, $title);
        if ($audiodb) {
            $genre = $audiodb['strGenre'] ?? null;
            $style = $audiodb['strStyle'] ?? null;
            $mood  = $audiodb['strMood'] ?? null;
            $theme = $audiodb['strTheme'] ?? null;
        }
    }

    // 3. Try MusicBrainz for tags if still missing
    if (!$genre) {
        $tags = queryMusicBrainzTags($artist, $title);
        $genre = implode(',', array_slice($tags, 0, 3));
    }

$stmt = $pdo->prepare("
    INSERT INTO tracks (
        spotify_id, title, artist, album, duration, popularity,
        bpm, `key`, camelot, energy, danceability,
        genre, style, mood, theme
    ) VALUES (
        :spotify_id, :title, :artist, :album, :duration, :popularity,
        :bpm, :key, :camelot, :energy, :danceability,
        :genre, :style, :mood, :theme
    )
    ON DUPLICATE KEY UPDATE
        bpm = VALUES(bpm), `key` = VALUES(`key`), camelot = VALUES(camelot),
        energy = VALUES(energy), danceability = VALUES(danceability),
        genre = VALUES(genre), style = VALUES(style),
        mood = VALUES(mood), theme = VALUES(theme)
");


$stmt->execute([
    ':spotify_id'   => $trackId,
    ':title'        => $title,
    ':artist'       => $artist,
    ':album'        => $album,
    ':duration'     => $duration,
    ':popularity'   => $popularity,
    ':bpm'          => $bpm,
    ':key'          => $key,
    ':camelot'      => $camelot,
    ':energy'       => $energy,
    ':danceability' => $danceability,
    ':genre'        => $genre,
    ':style'        => $style,
    ':mood'         => $mood,
    ':theme'        => $theme
]);

    echo "✅ Saved: \"$title\" by $artist\n";
}
