#!/usr/bin/python3

# Copyright 2025, Louis-Philippe Véronneau <pollo@debian.org>
#
# This script is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This script is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this script. If not, see <http://www.gnu.org/licenses/>.

"""
scan the music directory and generate the End of Year listing and covers

./gen-eoy.py $dir
"""

import glob
import os
import shutil
import sys

from datetime import datetime

from PIL import Image


def scan_dir(music_dir):
    """Generate a list of all 3nd level directories, sorted by modified date"""
    depth3 = glob.glob(music_dir + '/*/*')
    dir_list = list(filter(lambda f: os.path.isdir(f), depth3))
    sort_me_dict = {}
    this_year = datetime.fromisoformat('2025-01-01')
    for directory in dir_list:
        last_modified = os.path.getmtime(directory)
        if datetime.fromtimestamp(last_modified) >= this_year:
            sort_me_dict[directory] = last_modified
    sorted_dict = dict(sorted(sort_me_dict.items(),
                              key=lambda item: item[1],
                              reverse=True))
    dir_list = list(sorted_dict.keys())
    return dir_list


def jpg_or_png(album_path):
    """Find if the album cover is jpg or png"""
    tcover = False
    if os.path.exists(os.path.join(album_path, 'cover.jpg')):
        tcover = 'jpg'
    elif os.path.exists(os.path.join(album_path, 'cover.png')):
        tcover = 'png'
    return tcover


def copy_cover(album_path, tcover, tmpdir):
    """Copy the album cover to the common cover directory"""
    root, artist, album = album_path.split('/')
    cover_path = os.path.join(album_path, f'cover.{tcover}')
    dest_path = os.path.join(tmpdir, f'{artist} - {album}.{tcover}')
    shutil.copy(cover_path, dest_path)
    return dest_path


def format_cover(cover_path):
    """Resize cover to 500x500 and transcode it to JPEG"""
    with Image.open(cover_path) as img:
        img_resized = img.resize((500, 500))
        extension = os.path.splitext(cover_path)[1][1:]
        remove = False
        if extension == 'png':
            remove = True
            img_resized = img_resized.convert('RGB')
            cover_path_png = cover_path
            cover_path = cover_path.replace('png', 'jpg')
        img_resized.save(cover_path, 'JPEG')
        if remove:
            os.remove(cover_path_png)


def manage_covers(album_path):
    """Manage the steps to deal with the album covers"""
    tmpdir = '/tmp/EndOfYear'
    if not os.path.isdir(tmpdir):
        os.mkdir(tmpdir)
    tcover = jpg_or_png(album_path)
    if tcover:
        cover_path = copy_cover(album_path, tcover, tmpdir)
        format_cover(cover_path)
    else:
        print(f'{album_path} does not have an album cover')


def generate_html(album_path):
    """Generate the HTML snippet for an album"""
    root, artist, album = album_path.split('/')
    name = f'{artist} - {album}'
    snippet =(
        '<div class="grid-item">\n'
        '  <a href="">\n'
        f'    <img src="MEDIA_PATH/{name}.jpg" style="width: 100%;" title="{name}" alt="{name}">\n'
        '  </a>\n'
        '</div>\n')
    return snippet


def main():
    """Main function"""
    music_dir = sys.argv[1]
    dir_list = scan_dir(music_dir)
    html_code = ''
    for album_path in dir_list:
        manage_covers(album_path)
        html_code += generate_html(album_path)
    with open('/tmp/EndOfYear/html_snippet.html', 'w',  encoding='utf-8') as html:
        html.write(html_code)


if __name__ == "__main__":
    main()
