import os
import click
import yaml
import eyed3
from eyed3.core import Date


@click.command()
@click.option("--config", prompt="Config path", help="A path to the yaml config")
def run(config):
    config_dir = os.path.dirname(config)
    data = read_one_block_of_yaml_data(config)
    if isinstance(data, list):
        for track in data:
            print(track["title"])
            audiofile = eyed3.load(f"{config_dir}/{track["file"]}")

            audiofile.initTag()
            
            # Set tags
            audiofile.tag.artist = track["artist"]
            audiofile.tag.album = track["album"]
            audiofile.tag.title = track["title"]
            audiofile.tag.track_num = track["number"]
            audiofile.tag.copyright = track["copyright"]
            audiofile.tag.comments.set(track["comment"])
            date_str = track["release_date"]
            date_obj = Date.parse(date_str)
            audiofile.tag.original_release_date = date_obj
            audiofile.tag.release_date = date_obj
            with open(f"{config_dir}/{track["cover"]}", "rb") as cover_art:
                audiofile.tag.images.set(
                    3, cover_art.read(), "image/png", "Cover (front)"
                )
            with open(f"{config_dir}/{track["lyrics"]}", "r", encoding="utf-8") as f:
                text = f.read()
                audiofile.tag.lyrics.set(text)
            audiofile.tag.save()
    else:
        raise Exception("Wrong data type, expected list")


def read_one_block_of_yaml_data(filename):
    with open(filename) as f:
        return yaml.safe_load(f)
    raise Exception("File doesn't exist")


if __name__ == "__main__":
    run()
