"""Download full data about the top 50 tracks.

Author: CS149 Faculty
Version: 11/19/2024
"""

import json
import time
import requests

API_KEY = "TODO ADD YOUR KEY HERE"
API_URL = "https://ws.audioscrobbler.com/2.0/"


def fetch_track_info(artist_name, track_name):
    """Get the metadata for a track on Last.fm.

    Args:
        artist_name (str): The artist name.
        track_name (str): The track name.

    Returns:
        dict: JSON response from Last.fm API.
    """
    params = {
        "method": "track.getinfo",
        "api_key": API_KEY,
        "format": "json",
        "artist": artist_name,
        "track": track_name,
    }
    print("\nCalling track.getinfo...")
    response = requests.get(API_URL, params)
    print(response.headers)
    data = response.json()
    return data.get("track")


def fetch_top_tracks():
    """Store the top tracks in a json file."""

    # Get the top tracks chart
    params = {
        "method": "chart.gettoptracks",
        "api_key": API_KEY,
        "format": "json"
    }
    print("\nCalling chart.gettoptracks...")
    response = requests.get(API_URL, params)
    print(response.headers)

    # Extract the tracks list
    data = response.json()
    tracks = data["tracks"]["track"]
    print("Received", len(tracks), "tracks")

    # Save the top tracks to a file
    with open("toptracks.json", "w") as file:
        json.dump(tracks, file, indent=4)

    # Get full info about each track
    fulltracks = []
    for track in tracks:
        artist_name = track["artist"]["name"]
        track_name = track["name"]
        info = fetch_track_info(artist_name, track_name)
        if info:
            fulltracks.append(info)
        # Wait 2 seconds between requests to avoid being blocked
        time.sleep(2)

    # Save the full tracks to a file
    with open("fulltracks.json", "w") as file:
        json.dump(fulltracks, file, indent=4)


if __name__ == "__main__":
    fetch_top_tracks()
