from flask import Blueprint, request, abort
from os import getenv as env
from urllib.parse import quote
import requests

bp = Blueprint("music", __name__)

@bp.route("/metadata")
def metadata():
    if not request.args.get("recording_name"):
        abort(400, "Recording name is required")
    if not request.args.get("artist_name"):
        abort(400, "Artist name is required")

    data = requests.get(
        f"https://api.listenbrainz.org/1/metadata/lookup/?recording_name={quote(request.args.get("recording_name"))}&artist_name={quote(request.args.get("artist_name"))}&metadata=true&inc=artist+tag+release",
        headers={
            "Authorization": f"Token {env("LISTENBRAINZ_TOKEN")}"
        }
    )

    if data.status_code == 200:
        return data.json()
    else:
        abort(500, "Failed to retrieve metadata")