#!/usr/bin/env nix-shell
#! nix-shell -i python3 --pure
#! nix-shell -p python3 python3Packages.coloredlogs python3Packages.r128gain

# TODO r128gain is not maintainted anymore

# Normalisation is done at the default of each program,
# which is usually -89.0 dB

# TODO The simplifications/fixes I've done makes it consider
# multi-discs albums as multiple albums

import logging
import os
import sys
import typing

import coloredlogs
import r128gain

coloredlogs.install(level="DEBUG", fmt="%(levelname)s %(message)s")
log = logging.getLogger()

# TODO Remove debug

# Constants
FORCE = "-f" in sys.argv
if FORCE:
    sys.argv.remove("-f")
if len(sys.argv) >= 2:
    SOURCE_FOLDER = os.path.realpath(sys.argv[1])
else:
    SOURCE_FOLDER = os.path.join(os.path.expanduser("~"), "Musiques")


def isMusic(f: str) -> bool:
    ext = os.path.splitext(f)[1][1:].lower()
    return ext in r128gain.AUDIO_EXTENSIONS


# Get album paths
log.info("Listing albums and tracks")
albums = list()
singleFiles = list()
for root, dirs, files in os.walk(SOURCE_FOLDER):
    folder_has_music = False
    for f in files:
        if isMusic(f):
            folder_has_music = True
            fullPath = os.path.join(root, f)
            singleFiles.append(fullPath)

    if folder_has_music:
        albums.append(root)

# log.info("Processing single files")
# r128gain.process(singleFiles, album_gain=False,
#                  skip_tagged=not FORCE, report=True)

for album in albums:
    albumName = os.path.relpath(album, SOURCE_FOLDER)
    log.info("Processing album {}".format(albumName))

    musicFiles = list()
    for f in os.listdir(album):
        if isMusic(f):
            fullPath = os.path.join(album, f)
            musicFiles.append(fullPath)

    if not musicFiles:
        continue

    r128gain.process(musicFiles, album_gain=True, skip_tagged=not FORCE, report=True)
    print("==============================")