#!/usr/bin/env python3
from sys import argv
from pathlib import Path
from shutil import copy2
import eyed3
import logging
import re
import os

# disable eyeD3 warning logs
logging.getLogger("eyed3.mp3.headers").setLevel(logging.CRITICAL)

song_path = argv[1]

copy2(song_path, "/home/fmcruz/Desktop/.temp.mp3")

song = eyed3.load(song_path)
new_song = eyed3.load("/home/fmcruz/Desktop/.temp.mp3")

track_number = str(song.tag.track_num[0]).zfill(2)
artist = song.tag.artist
album_artist = song.tag.album_artist

genre = song.tag.genre
if str(genre).startswith('('):
    genre = re.search(r"(?<=\)).*", str(song.tag.genre)).group(0)


if album_artist != artist:
    if artist.startswith(album_artist):
        # if it has feat
        feat = artist[len(album_artist) :]
        new_song.tag.title += feat[:0] + " (" + feat[1:] + ")"
    else:
        # if the artist and album artist are completely different
        new_song.tag.title += " by " + artist
    # in case of changes
    new_song.tag.artist = album_artist
    new_song.tag.save()

new_song_path = "{}{} - {}/{} - {} - Cd {}/{}. {}.mp3".format(
    str(Path.home()) + "/Desktop/to_phone/",
    album_artist.replace("/"," "),
    genre,
    str(new_song.tag.recording_date),
    song.tag.album.replace("/"," "),
    str(new_song.tag.disc_num[0]),
    track_number,
    new_song.tag.title.replace("/"," "),
)

os.renames("/home/fmcruz/Desktop/.temp.mp3", new_song_path)
