import os
from api import AppleMusic
import unicodedata

def check_explicitness(album_link):
    # Initialize AppleMusic object
    apple_music = AppleMusic(cache="./cache", sync=1, skipVideo=False)

    # Get album ID and name from the provided link
    album_id = album_link.split('/')[-1].split('?')[0]  # Extract album ID from the URL
    album_name = album_link.split('/')[-2]  # Extract album name from the URL

    # Construct valid album link
    valid_album_link = f"https://music.apple.com/us/album/{album_name}/{album_id}"

    # Print constructed URL
    print("Constructed URL:", valid_album_link)

    # Get information about the album from the constructed valid link
    album_info = apple_music.getInfo(valid_album_link)

    # Check if any tracks are explicit
    is_explicit = any(track_info.get('rating', '') == 'Explicit' for track_info in album_info["streams"])

    # Modify album name and add [E] if explicit
    if is_explicit:
        album_name += " [E]"

    # Ask user for the directory to save the file
    save_directory = input("Please provide the directory path to save the 'album_infosse.txt' file: ")
    file_path = os.path.join(save_directory, "album_infosse.txt")
    print("album_infosse.txt -- saved")

    with open(file_path, "w") as file:
        # Write modified album name to file
        file.write(f"Album: {album_name}\n\n")
        file.write(f"Album_ID: {album_id}\n\n")

        # Write track details to file
        for track_info in album_info["streams"]:
            track_name = track_info['song']
            explicitness = track_info.get('rating', 'Not Explicit')
            credits = track_info.get('credits', {})
            credits_str = ", ".join([f"{role}: {', '.join(artists)}" for role, artists in credits.items()])

            # Add [E] to track name if explicit
            if explicitness == 'Explicit':
                track_name += " [E]"

            file.write(f"Track: {track_name}\n")
            file.write(f"Explicitness: {explicitness}\n")
            file.write(f"Credits: {credits_str}\n\n")

    # Rename album and track files
    rename_album_and_tracks(save_directory, album_name, album_info["streams"])

def rename_album_and_tracks(directory, album_name, tracks):
    while True:
        # Get the actual case-sensitive album directory name (handling potential errors)
        try:
            existing_album_dir = next(d for d in os.listdir(directory) if d.lower() == album_name.lower())
        except StopIteration:
            print(f"Error: Album directory '{album_name}' not found in '{directory}'")
            choice = input("Do you want to choose a different directory? (y/n): ").lower()
            if choice == 'y':
                directory = input("Enter the new directory path: ")
                continue  # Try again with the new directory
            else:
                return  # Exit the function if the user doesn't want to choose a different directory

        album_directory = os.path.join(directory, existing_album_dir)
        break  # Exit the loop if the directory is found

    try:
        os.rename(os.path.join(directory, album_name.replace(" [E]", "")), album_directory)  # Rename without [E] if it exists
    except FileNotFoundError:
        print(f"Warning: Album directory '{album_name}' not found for renaming.")

    for track_info in tracks:
        old_track_name = track_info['song']
        track_base_name = old_track_name.rsplit(".", 1)[0]  # Extract track name without extension

        # Normalize track name and file names using Unicode normalization
        track_base_name = unicodedata.normalize("NFKD", track_base_name)

        # Generate possible file name variations 
        possible_file_names = []
        possible_file_names.append(f"{{:02d}}. {track_base_name}.m4a")  # With track number
        possible_file_names.append(f"{track_base_name}.m4a")  # Without track number

        # Handle special characters and variations (including apostrophes, periods, and "feat." inconsistencies)
        for special_chars in [["(", ")"], ["[", "]"], ["  ", " "], [" - ", " "], [" – ", " "], ["'", ""], [".", ""]]:
            for file_name_format in possible_file_names.copy():
                modified_name = file_name_format.replace(special_chars[0], special_chars[1])
                possible_file_names.append(modified_name)

        # Handle "feat." inconsistencies separately 
        for file_name_format in possible_file_names.copy():
            modified_name_feat = file_name_format.replace("feat.", "ft.")
            modified_name_feat_space = file_name_format.replace("feat. ", "ft. ") 
            possible_file_names.append(modified_name_feat)
            possible_file_names.append(modified_name_feat_space)

        # Handle additional variations for featuring artists (e.g., "with", "&")
        for file_name_format in possible_file_names.copy():
            modified_name_with = file_name_format.replace("feat.", "with")
            modified_name_and = file_name_format.replace("feat.", "&")
            possible_file_names.append(modified_name_with)
            possible_file_names.append(modified_name_and)

        # Find the actual file name in the directory (case-insensitive)
        found_file = False
        for file_name_format in possible_file_names:
            try:
                actual_file_name = next(
                    f for f in os.listdir(album_directory) 
                    if f.lower() == file_name_format.format(tracks.index(track_info) + 1).lower()
                )
                found_file = True
                break  # Exit the loop if a matching file is found
            except StopIteration:
                pass  # Try the next file name variation

        if not found_file:
            print(f"Warning: File not found for track '{old_track_name}'")
            continue  # Skip to the next track if no matching file is found

        try:
            new_track_name = f"{track_base_name} [E].m4a" if track_info.get('rating', '') == 'Explicit' else actual_file_name
            os.rename(os.path.join(album_directory, actual_file_name), os.path.join(album_directory, new_track_name))
        except FileNotFoundError:
            print(f"Warning: File '{actual_file_name}' not found for renaming.")

        new_track_name = f"{track_base_name} [E].m4a" if track_info.get('rating', '') == 'Explicit' else actual_file_name
        os.rename(os.path.join(album_directory, actual_file_name), os.path.join(album_directory, new_track_name))

# Function to read the Apple Music album link from a file
def read_album_link_from_file(file_path):
    with open(file_path, "r") as file:
        album_link = file.readline().strip()
    return album_link

# Example usage
if __name__ == "__main__":
    # Ask user for the directory where apple_music_link.txt is located
    directory = input("Please provide the directory path where 'apple_music_link.txt' is located: ")
    file_path = os.path.join(directory, "apple_music_link.txt")
    
    # Read the Apple Music album link from the file
    album_link = read_album_link_from_file(file_path)
    
    # Check explicitness of the album
    check_explicitness(album_link)


(myenv) C:\Users\ILEG-i5-11\Desktop\Needed\API1 full response with AUTH>python gter.py
Please provide the directory path where 'apple_music_link.txt' is located: D:\ALAC features(enabled)\apple-music-alac-atmos-downloader\AM-DL downloads\Demi Lovato\REVAMPED
[16:20:21] [ManzanaCore] INFO: Checking access token found in cache...
[16:20:21] [ManzanaCore] INFO: Checking media-user-token...
Constructed URL: https://music.apple.com/us/album/revamped/1697368699
[16:20:24] [ManzanaCore] INFO: Fetching api response...
[16:20:24] [ManzanaCore] INFO: Using the previous response found in cache...
Please provide the directory path to save the 'album_infosse.txt' file: D:\ALAC features(enabled)\apple-music-alac-atmos-downloader\AM-DL downloads\Demi Lovato\REVAMPED
album_infosse.txt -- saved
Error: Album directory 'revamped' not found in 'D:\ALAC features(enabled)\apple-music-alac-atmos-downloader\AM-DL downloads\Demi Lovato\REVAMPED'
Do you want to choose a different directory? (y/n): y
Enter the new directory path: D:\ALAC features(enabled)\apple-music-alac-atmos-downloader\AM-DL downloads\Demi Lovato\
Warning: File not found for track 'Sorry Not Sorry (feat. Slash) [Rock Version]'
Warning: File not found for track 'La La Land (feat. Nita Strauss) [Rock Version]'