import base64
import acrcloud
import os
import eyed3
import requests
import json
import re
from my_shazam_utility import shazam_recognize_song
from applemusic_api import AppleMusicApi
from Acrcloudretrieve import recognize_song, set_id3_tags_mp3
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover

def load_config():
    with open('D:/Eurydice/Encompassing Data by discerning/config/config.json', 'r') as config_file:
        config_data = json.load(config_file)
    return config_data

# Load the configuration on script start
config = load_config()

# Now also load Spotify credentials
CLIENT_ID = config['Spotify']['CLIENT_ID']
CLIENT_SECRET = config['Spotify']['CLIENT_SECRET']

def get_user_choice():
    # Display a header
    print("=" * 50)
    print("Welcome to the Song Recognition Service!")
    print("=" * 50)

    # Provide instructions and options
    print("\nPlease select the recognition service you'd like to use:\n")
    print("  1: YoutubeACR - Fast and accurate music recognition")
    print("  2: Shazam - Discover music, artists, and lyrics in seconds")
    
    # Separator for aesthetic purposes
    print("-" * 50)

    # Input prompt
    choice = input("Enter your choice (1 or 2) and press Enter: ")
    
    # More flair to indicate processing/input received
    print("\n" + "." * 25 + " Processing " + "." * 25 + "\n")

    return choice

# Your Spotify authentication and song search functions:
def authenticate_spotify(client_id, client_secret):
    auth_url = 'https://accounts.spotify.com/api/token'
    client_creds = f"{client_id}:{client_secret}"
    client_creds_b64 = base64.b64encode(client_creds.encode())
    headers = {'Authorization': f'Basic {client_creds_b64.decode()}'}
    data = {'grant_type': 'client_credentials'}
    response = requests.post(auth_url, headers=headers, data=data)
    access_token = response.json().get('access_token')
    return access_token

def search_spotify_for_song(access_token, artist_name, title):
    base_url = "https://api.spotify.com/v1/search"
    query = f"{title} artist:{artist_name}"
    headers = {"Authorization": f"Bearer {access_token}"}
    params = {"q": query, "type": "track", "limit": 1}
    response = requests.get(base_url, headers=headers, params=params)
    results = response.json()
    try:
        track_info = results['tracks']['items'][0]
        return track_info
    except IndexError:
        print("Song not found on Spotify.")
        return None

# Modify your process_audio_file function to incorporate Spotify search
def process_audio_file(audio_file_path):
    # Identify song using Shazam
    shazam_data = shazam_recognize_song(audio_file_path)
    
    if shazam_data:
        artist_name = shazam_data['track']['subtitle']
        title = shazam_data['track']['title']
        print(f"Identified Song: {artist_name} - {title}")
        
        # Authenticate with Spotify
        access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
        
        # Search for song on Spotify
        song_info = search_spotify_for_song(access_token, artist_name, title)
        
        if song_info:
            track_number = song_info['track_number']
            print(f"Track Number on Spotify: {track_number}")
        else:
            print("Song not found on Spotify.")
    else:
        print("Song could not be identified.")

if __name__ == "__main__":
    user_choice = get_user_choice()
    audio_file_path = 'D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3'
    if user_choice == '1':
        print("\n" + "." * 15 + " ᴜsɪɴɢ YᴏᴜᴛᴜʙᴇACR " + "." * 15 + "\n")
        song_tags = recognize_song(audio_file_path)

        if song_tags:
            print(f'Song identified: {song_tags}')
            set_id3_tags_mp3(audio_file_path, song_tags)

            artist_name = song_tags.get('artists')[0].get('name')
            song_title = song_tags.get('title')
        
            safe_artist_name = re.sub(r'[/\:?"<>|]', '', artist_name)
            safe_song_title = re.sub(r'[/\:?"<>|]', '', song_title)
            new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
        
            new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
            os.rename(audio_file_path, new_file_path)
            print(f"File has been renamed to: {new_file_name}")

        else:
            print('Could not identify the song in YᴏᴜᴛᴜʙᴇACR.')

        apple_music_api = AppleMusicApi(Exception)  # Initialize AppleMusicApi with necessary authentication
        apple_music_api.get_access_token()
        track_results = apple_music_api.search('songs', f"{artist_name} - {song_title}")
        if track_results:
            track_id = track_results[0]['id']
            album_artwork_url_template = track_results[0]['attributes']['artwork']['url']

            save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
        else:
            print("Song not found on Apple Music.")
        
        lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
        if lrc_lyrics:
            lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f"{safe_artist_name} - {safe_song_title}.lrc")
            with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
                lrc_file.write(lrc_lyrics)
            print(f"Saved LRC file to: {lrc_file_path}")
        else:
            print("Could not get the lyrics.")

    elif user_choice == '2':
        print("\n" + "." * 15 + " ᴜsɪɴɢ Sʜᴀᴢᴀᴍ " + "." * 15 + "\n")
        song_tags = shazam_recognize_song(audio_file_path)
        print(song_tags)
    else:
        print("Invalid choice. Exiting.")
        exit()

        

after selecting 2 option :
these: must execute

# Your Spotify authentication and song search functions:
def authenticate_spotify(client_id, client_secret):
    auth_url = 'https://accounts.spotify.com/api/token'
    client_creds = f"{client_id}:{client_secret}"
    client_creds_b64 = base64.b64encode(client_creds.encode())
    headers = {'Authorization': f'Basic {client_creds_b64.decode()}'}
    data = {'grant_type': 'client_credentials'}
    response = requests.post(auth_url, headers=headers, data=data)
    access_token = response.json().get('access_token')
    return access_token

def search_spotify_for_song(access_token, artist_name, title):
    base_url = "https://api.spotify.com/v1/search"
    query = f"{title} artist:{artist_name}"
    headers = {"Authorization": f"Bearer {access_token}"}
    params = {"q": query, "type": "track", "limit": 1}
    response = requests.get(base_url, headers=headers, params=params)
    results = response.json()
    try:
        track_info = results['tracks']['items'][0]
        return track_info
    except IndexError:
        print("Song not found on Spotify.")
        return None

# Modify your process_audio_file function to incorporate Spotify search
def process_audio_file(audio_file_path):
    # Identify song using Shazam
    shazam_data = shazam_recognize_song(audio_file_path)
    
    if shazam_data:
        artist_name = shazam_data['track']['subtitle']
        title = shazam_data['track']['title']
        print(f"Identified Song: {artist_name} - {title}")
        
        # Authenticate with Spotify
        access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
        
        # Search for song on Spotify
        song_info = search_spotify_for_song(access_token, artist_name, title)
        
        if song_info:
            track_number = song_info['track_number']
            print(f"Track Number on Spotify: {track_number}")
        else:
            print("Song not found on Spotify.")
    else:
        print("Song could not be identified.")