import requests
from mutagen import File
from mutagen.id3 import ID3, USLT, ID3NoHeaderError
import os

def fetch_lyrics(artist: str, album: str, track: str, duration: int = 0) -> str:

    skip_artists = [
        "shurupis",
        "unknown",
		"Unknown"
    ]

    skip_album = [
        "unknown",
		"Unknown"
    ]

    if artist in skip_artists or album in skip_album:
        return ""


    url = "https://lrclib.net/api/get"
    params = {
        "artist_name": artist,
        "track_name": track,
        "album_name": album,
        "duration": duration,
    }
    try:
        resp = requests.get(url, params=params, timeout=10)
        if resp.status_code != 200:
            try:
                err = resp.json()
                print(err.get("error"), "-", err.get("message"))
            except ValueError:
                print("HTTPError", resp.status_code)
            return ""
        data = resp.json()
        if "error" in data:
            print(data.get("error"), "-", data.get("message"))
            return ""
        return data.get("syncedLyrics", "")
    except requests.RequestException as e:
        print(type(e).__name__, "-", str(e))
        return ""
    except ValueError as e:
        print(type(e).__name__, "-", str(e))
        return ""


def write_lyrics(file_path, lyrics_text, lang="eng"):
	"""
	Writes lyrics text into tags recognized by Navidrome.
	Provides detailed logs and success/failure info.
	"""

	ext = os.path.splitext(file_path)[1].lower()
	print(f"[INFO] Processing file: {file_path} (extension: {ext})")

	try:
		# ---------- MP3 ----------
		if ext == ".mp3":
			print("[INFO] Detected MP3 file")
			try:
				tags = ID3(file_path)
				print("[INFO] Existing ID3 tags loaded")
			except ID3NoHeaderError:
				tags = ID3()
				print("[INFO] No ID3 header found, creating new tags")

			tags.delall("USLT")
			print("[INFO] Removed existing USLT frames (lyrics)")

			tags.add(
				USLT(
					encoding=3,   # UTF-8
					lang=lang,
					desc="",
					text=lyrics_text
				)
			)
			tags.save(file_path)
			print("[SUCCESS] Lyrics written to MP3 tags")
			return

		# ---------- FLAC / OGG / OPUS ----------
		audio = File(file_path)
		if audio is None:
			print(f"[ERROR] Unsupported or unrecognized file format: {file_path}")
			return

		if ext in {".flac", ".ogg", ".opus"}:
			print(f"[INFO] Detected {ext.upper()} file")
			audio["LRC"] = lyrics_text
			audio["SYNCEDLYRICS"] = lyrics_text
			audio.save()
			print(f"[SUCCESS] Lyrics written to {ext.upper()} tags")
			return

		# ---------- Fallback ----------
		if audio.tags is not None:
			print("[INFO] Using fallback tag writing")
			audio["LYRICS"] = lyrics_text
			audio.save()
			print("[SUCCESS] Lyrics written using fallback tags")
			return

		print(f"[WARNING] No suitable tag frame found for {file_path}")

	except Exception as e:
		print(f"[ERROR] Failed to write lyrics to {file_path}: {e}")

