#!/usr/bin/python3
import os
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, USLT, ID3NoHeaderError

# --- CONFIGURATION ---
# Set the path to your music folder here
MUSIC_FOLDER = r"/mnt/smb/media/music"

# Set to True to overwrite existing lyrics. Set to False to skip them.
FORCE_OVERWRITE = False
# ---------------------

def embed_lyrics_to_mp3(mp3_path, lrc_path):
    try:
        # Load or initialize the ID3 tags for the MP3
        try:
            audio = MP3(mp3_path, ID3=ID3)
        except ID3NoHeaderError:
            audio = MP3(mp3_path)
            audio.add_tags()

        # Check if a USLT frame already exists
        # Mutagen keys use the format: 'USLT:desc:lang' (e.g., 'USLT::eng')
        if audio.tags and 'USLT::eng' in audio.tags and not FORCE_OVERWRITE:
            print(f"⏩ Skipped (Lyrics already exist): {os.path.basename(mp3_path)}")
            return

        # Read the raw contents of the LRC file
        with open(lrc_path, 'r', encoding='utf-8', errors='ignore') as f:
            lyrics_text = f.read()

        # USLT frame arguments:
        # encoding=3 (UTF-8), lang='eng' (3-letter language code), desc='' (description), text=lyrics_text
        audio.tags.add(USLT(encoding=3, lang='eng', desc='', text=lyrics_text))

        # Save changes explicitly in ID3v2.3 format for maximum player compatibility
        audio.save(v2_version=3)

        status = "Overwrote" if FORCE_OVERWRITE else "Embedded"
        print(f"✅ Successfully {status} lyrics into: {os.path.basename(mp3_path)}")

    except Exception as e:
        print(f"❌ Failed to process {os.path.basename(mp3_path)}: {e}")

def scan_and_embed(folder):
    print(f"Scanning directory for MP3 and LRC pairs... (Force Overwrite: {FORCE_OVERWRITE})")
    for root, _, files in os.walk(folder):
        for file in files:
            if file.lower().endswith('.mp3'):
                mp3_path = os.path.join(root, file)
                # Build the expected .lrc path matching the file name
                lrc_path = os.path.splitext(mp3_path)[0] + '.lrc'
                
                if os.path.exists(lrc_path):
                    embed_lyrics_to_mp3(mp3_path, lrc_path)

if __name__ == "__main__":
    if os.path.exists(MUSIC_FOLDER):
        scan_and_embed(MUSIC_FOLDER)
        print("\nAll done! Remember to trigger a 'Full Scan' in your Navidrome Web UI settings.")
    else:
        print(f"Error: The directory '{MUSIC_FOLDER}' does not exist. Please update the MUSIC_FOLDER variable in the script.")
