import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os
from dotenv import load_dotenv

load_dotenv()


def get_spotify_client():
    client_id = os.getenv("SPOTIFY_CLIENT_ID")
    client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
    redirect_uri = os.getenv("SPOTIFY_REDIRECT_URI", "http://localhost:8888/callback")

    if not client_id or not client_secret:
        raise ValueError(
            "Missing spotify credentials. Ensure SPOTIFY_CLIENT_ID and"
            " SPOTIFY_CLIENT_SECRET are set in your .env file"
        )

    scope = (
        "playlist-read-private playlist-read-collaborative user-read-email user-read-playback-state"
    )
    sp_oauth = SpotifyOAuth(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri=redirect_uri,
        scope=scope,
        cache_path=".spotify_cache",
    )

    sp = spotipy.Spotify(auth_manager=sp_oauth)
    return sp
