import acrcloud
import os
import eyed3
import requests
import json
import re
from applemusic_api import AppleMusicApi
from acrcloud.recognizer import ACRCloudRecognizer
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover

ACR_HOST = ""
ACR_ACCESS_KEY = ""
ACR_ACCESS_SECRET = ""

config = {
    'host': ACR_HOST,
    'access_key': ACR_ACCESS_KEY,
    'access_secret': ACR_ACCESS_SECRET,
    'timeout': 10  # seconds
}
dir(acrcloud)

recognizer = ACRCloudRecognizer(config)

def recognize_song(audio_file_path):
    buffer = open(audio_file_path, 'rb').read()
    result = recognizer.recognize_by_filebuffer(buffer, 0)
    try:
        result_dict = json.loads(result)
        return result_dict['metadata']['music'][0]
    except (KeyError, IndexError, json.JSONDecodeError) as e:
        print(f"Error while parsing result: {e}")
        return None

def set_id3_tags_mp3(audio_file_path, tags):
    audio_file = eyed3.load(audio_file_path)
    if not audio_file.tag:
        audio_file.initTag()

    audio_file.tag.artist = tags.get('artists')[0].get('name')
    audio_file.tag.album = tags.get('album').get('name')
    audio_file.tag.album_artist = tags.get('artists')[0].get('name')
    audio_file.tag.title = tags.get('title')

    release_date = tags.get('release_date')
    if release_date and len(release_date) >= 4:
        year_string = release_date[:4]
        try:
            year = int(year_string)
            if hasattr(eyed3.id3.tag, 'Date'):
                audio_file.tag.recording_date = eyed3.id3.tag.Date(year)
            else:
                audio_file.tag.setTextFrame("TDRC", year_string)
        except ValueError:
            print(f"Invalid date format in the tag: {release_date}")

    audio_file.tag.genre = tags.get('genres')[0].get('name')
    audio_file.tag.publisher = "KARTHIK"
    
    audio_file.tag.copyright = tags.get('label', '')
    audio_file.tag.comments.set(u"Explicit: Yes")  
    
    audio_file.tag.save(version=eyed3.id3.ID3_V2_3)

    audio_file.tag.save()

if __name__ == "__main__":
    audio_file_path = 'D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file_1.mp3'
    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}")

        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.")

    else:
        print('Could not identify the song.')


using shazam and ACRcloud (use both) to identify the song (if one is failed then use another one) (if both are successful then use both to recognise the song and tag the audio file according to all fields like track number, etc - the parameters which are fetched from shazam)