from syncedlyrics import search
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
import os
import threading

songs = json.load(open("songs.json", encoding="utf8"))

os.makedirs("lyrics", exist_ok=True)

lock = threading.Lock()


def download_lyrics(song):
    fname = song["name"].replace("/", "_") + ".lrc"
    path = os.path.join("lyrics", fname)

    if os.path.exists(path):
        return f"SKIP {song['name']}"

    query = f"{song['name']} {song['artist']}"

    try:
        lrc = search(
            query,
            enhanced=True
        )

        if lrc:
            with lock:
                with open(
                    path,
                    "w",
                    encoding="utf8"
                ) as f:
                    f.write(lrc)

            return f"OK   {song['name']}"

        return f"MISS {song['name']}"

    except Exception as e:
        return f"FAIL {song['name']} -> {e}"


MAX_THREADS = 20

with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:

    futures = [
        executor.submit(download_lyrics, song)
        for song in songs
    ]

    for future in as_completed(futures):
        print(future.result())
