<?php
require_once 'config.php';
require_once 'spotify_api.php';
require_once 'lastfm_api.php';

function convertToCamelot(?int $key, ?int $mode): ?string {
    $camelotMap = [
        ['8A','8B'], ['3A','3B'], ['10A','10B'], ['5A','5B'],
        ['12A','12B'], ['7A','7B'], ['2A','2B'], ['9A','9B'],
        ['4A','4B'], ['11A','11B'], ['6A','6B'], ['1A','1B']
    ];
    return ($key !== null && $mode !== null && $key >= 0 && $key <= 11) ? $camelotMap[$key][$mode] : null;
}

function getAudioFeaturesFromKaggle($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 getAudioFeaturesFromAudioDB($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 getAudioFeaturesFromLastFM($artist, $title) {
    return getLastFMTrackTags($artist, $title);
}

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

    if (empty($track['id'])) {
        echo "⚠️ Skipping track with no ID: " . ($track['name'] ?? 'unknown') . "\n";
        return;
    }

    $trackId = $track['id'];
    $title = $track['name'] ?? 'Unknown Title';
    $artist = implode(', ', array_map(fn($a) => $a['name'], $track['artists'] ?? []));
    $album = $track['album']['name'] ?? 'Unknown Album';
    $duration = isset($track['duration_ms']) ? gmdate("i:s", (int)($track['duration_ms'] / 1000)) : null;
    $popularity = $track['popularity'] ?? null;

    $features = getAudioFeaturesFromKaggle($artist, $title);
    if (!$features) $features = getAudioFeaturesFromAudioDB($artist, $title);
    if (!$features) $features = getAudioFeaturesFromLastFM($artist, $title);

    $bpm = isset($features['tempo']) ? (float)$features['tempo'] : null;
    $key = isset($features['key']) && is_numeric($features['key']) ? (int)$features['key'] : null;
    $mode = isset($features['mode']) && is_numeric($features['mode']) ? (int)$features['mode'] : null;
    $camelot = convertToCamelot($key, $mode);
    $energy = $features['energy'] ?? null;
    $danceability = $features['danceability'] ?? null;
    $genre = $features['strGenre'] ?? $features['genre'] ?? null;
    $style = $features['strStyle'] ?? null;
    $mood = $features['strMood'] ?? null;
    $theme = $features['strTheme'] ?? null;

    $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)
    ");

    try {
        $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 "✅ Inserted: \"$title\" by $artist\n";
    } catch (PDOException $e) {
        echo "❌ Failed on track $title: " . $e->getMessage() . "\n";
    }
}
?>
