from pprint import pprint
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os
from bs4 import BeautifulSoup

URL = "https://www.billboard.com/charts/hot-100/"
CLIENT_ID = os.environ["CLIENT_ID"]
CLIENT_SECRET_ID = os.environ["CLIENT_SECRET_ID"]
REDIRECT_URL = "http://example.com"
TOKEN = os.environ["access_token"]

date = input("Enter the time you wish to search in (YYYY-MM-DD) Format:")

response = requests.get(url=f"{URL}{date}")
response = response.text
soup = BeautifulSoup(response, "html.parser")

title_file = soup.find_all(name="span", class_="chart-element__information__song text--truncate color--primary")
artist_file = soup.find_all(name="span", class_="chart-element__information__artist text--truncate color--secondary")
top_100_song = [f"{title.text}" for title in title_file]
top_100_artists = [f"{name.text}" for name in artist_file]

top_100_save = [f"{top_100_song[i]}-{top_100_artists[i]}\n" for i in range(0, len(top_100_artists))]

with open("top_100.txt", "w") as save_file:
    save_file.writelines(top_100_save)

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID,
                                               client_secret=CLIENT_SECRET_ID,
                                               redirect_uri=REDIRECT_URL,
                                               scope="playlist-modify-private"))
user_id = sp.current_user()['id']
play_list = sp.user_playlist_create(user=user_id, name=f"BeatsByBots-{date}", public=False, collaborative=False,
                                    description="This is a autogenerated playlist by a bot")
pprint(play_list)

with open("top_100.txt", "r") as file:
    top_songs = file.readlines()
    song_ids = []
    for song in top_songs:
        try:
            result = sp.search(song, 1)
            id = result["tracks"]["items"][0]["uri"]
            print(id)
            song_ids.append(id)
        except IndexError:
            print(f"Song not found {song}")
    pprint(song_ids)

uris = song_ids

user_id = sp.current_user()['id']
sp.playlist_add_items(play_list['id'], uris)
