# This Python file uses the following encoding: utf-8
"""This module contains utility scripts used by musi radiostation Conjurer"""
import time
import re
import os
import argparse

from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3


def update_metadata(folder_path):
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".mp3"):
                file_path = os.path.join(root, file)

                # Sample logic for guessing metadata from filename
                # Assuming the filename format is "Artist - Title.mp3"
                try:
                    artist, title = file.rsplit(" - ", 1)
                    title = title.replace(".mp3", "")
                except ValueError:
                    # If file name doesn't fit the expected pattern, skip
                    print(f"Skipping file due to unexpected format: {file}")
                    continue

                try:
                    # Load the mp3 file
                    audio = MP3(file_path, ID3=EasyID3)

                    # Update metadata
                    audio["artist"] = artist.strip()
                    audio["title"] = title.strip()

                    # Save changes
                    audio.save()
                    print(f"Updated metadata for: {file}")
                except Exception as e:
                    print(f"Failed to update metadata for {file}: {e}")


NAME = "/home/pi/Conjurer/persistence.log"


def print_top():
    """
    Prints the top 65 lines from a file specified by the NAME variable.
    """
    while True:
        line = ""
        buffer = ""
        with open(NAME, "r", encoding="utf-8") as f:
            for _ in range(45):
                line = f.readline()
                if re.match(".*mp3", line):
                    buffer += line
            print("=====================================")
            print(buffer)
            print("=====================================")
        time.sleep(180)


def main():
    parser = argparse.ArgumentParser(
        description="Perform operations on a directory of .mp3 files."
    )

    # Positional argument for choosing the function to execute
    parser.add_argument(
        "operation",
        type=str,
        choices=["update_metadata", "print_top"],
        help="Operation to perform: update_metadata or print_top.",
        default="print_top",
    )

    # Positional argument for folder path
    parser.add_argument("folder", type=str, help="Path to the folder to operate on.")

    args = parser.parse_args()
    if args.operation == "update_metadata":
        if args.folder:
            folder_to_scan = args.folder
        else:
            print("Please provide a folder path to scan.")
            raise ValueError("No folder path provided.")

    if args.operation == "update_metadata" and os.path.isdir(folder_to_scan):
        update_metadata(folder_to_scan)
    elif args.operation == "print_top":
        print_top()
    else:
        print(f"The specified path is not a directory: {folder_to_scan}")


if __name__ == "__main__":
    main()
