
from tqdm import tqdm

from src.Library import *
from src.helpers import *
from src.backends.spotify.SpotifyWebAPI import find_song, update_access_token

def generate_map(client_id, client_secret, local_lib : Library, spotify_lib : Library, output_dir):

    set_workdir(output_dir)

    update_access_token(client_id, client_secret)

    def find_local_songs_on_spotify():
        search_log = []

        total = len(local_lib.tracks)
        found_tracks_map = {}
        with tqdm(total=total, desc='Searching local songs on spotify') as pbar:
            for track in local_lib.tracks:

                parts = [track.title, track.artists[0].title if len(track.artists) else "", track.album.title]
                search_pattern = " ".join(p for p in parts if p)

                if search_pattern == "":
                    print(f"cannot generate search pattern for the track - {track.local_path}")
                    pbar.update(1)
                    continue

                found_tracks = find_song(search_pattern)[0:10]
                found_tracks_map[track.id] = found_tracks
                search_log.append({"path" : track.local_path, "search_pattern": search_pattern, "result" : found_tracks_map[track.id]})
                pbar.update(1)

        save_data(search_log, "spotify_search_log")
        save_data(found_tracks_map, "spotify_found_map")

        return found_tracks_map

    spotify_found_tracks = find_local_songs_on_spotify()

    spotify_user_track = {track.id for track in spotify_lib.tracks}

    spotify_pattern = {}
    for local_id, found_items in spotify_found_tracks.items():
        spotify_pattern[local_id] = {"score": 1.0, "items": []}

        if not len(found_items):
            continue

        for found_item in found_items:
            spotify_track_id = found_item['id']
            if spotify_track_id in spotify_user_track:
                spotify_pattern[local_id]['items'].append(spotify_track_id)

    save_data(spotify_pattern, "local_to_spotify_id_map")