#! /usr/bin/env python3

# This script is meant to update the tags on songs which are to be sync'd
# to my iPhone in order to allow for sane sorting.
#
# The iOS Music app, being horrible and whatnot, no longer allows the user
# to decide how albums are sorted. By default they appear to sort in
# reverse chronological order, which is backwards.
#
# If the date tags of two albums are equal, the Music app sorts by the
# album tag. This script works by setting all date tags to 9999 and
# prepending the date of each song to its album name.
#
# It's real sketchy, but it seems to work.

from __future__ import print_function

import os
import sys
import argparse
import traceback

# from mutagen.easyid3 import EasyID3 as mutagen_id3
from mutagen.id3 import ID3 as mutagen_id3
from mutagen.id3 import TYER, TDRC, TDAT, TALB, TSOA

audio_endings = ('.mp3', '.m4a')
possible_date_tags = ('TDRC', 'TYER', 'TDAT')
album_tag = 'TALB'

def add_sort_album_tags(path):
    for root, _, files in os.walk(path):
        audio_files = (name for name in files if name.endswith(audio_endings))
        for name in audio_files:
            filename = os.path.join(root, name)

            try:
                tags = mutagen_id3(filename)

            except Exception as exc:
                print(traceback.format_exc())
                print(exc)

                continue

            date_tag = None
            for tag in possible_date_tags:
                if (tag in tags.keys() and str(tags[tag].text[0]) < '3000'):
                    if date_tag is None:
                        date_tag = tag
                    else:
                        tags.delall(tag)

            if date_tag is not None and album_tag in tags.keys():
                sort_album = (str(tags[date_tag].text[0])[:4] +
                              u' - ' + tags[album_tag].text[0])
                tags.setall('TSOA', [TSOA(text=sort_album)])
                tags.setall('TALB', [TALB(text=sort_album)])

                tags.delall(date_tag)
                tags.setall('TDRC', [TDRC(text=u'9999')])

                tags.save()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Fix iOS Music album sorting.")
    parser.add_argument("path", help="Directory containing files to process.")
    args = parser.parse_args()
    add_sort_album_tags(args.path)
