"""
Spotify Web API — Search Track Demo
====================================
A minimal, ready-to-run example using the Client Credentials flow to search.

Get credentials (free):
    1. Log in at https://developer.spotify.com/dashboard
    2. Click "Create app", fill in any name/description.
    3. Open the app's Settings to copy the Client ID and Client Secret.

Setup:
    pip install requests
    export SPOTIFY_CLIENT_ID="..."
    export SPOTIFY_CLIENT_SECRET="..."

Run:
    python spotify_demo.py
"""

import os
import requests


def get_token() -> str:
    """Fetch an app-only access token via Client Credentials."""
    response = requests.post(
        "https://accounts.spotify.com/api/token",
        data={"grant_type": "client_credentials"},
        auth=(os.environ.get("SPOTIFY_CLIENT_ID"), os.environ.get("SPOTIFY_CLIENT_SECRET")),
    )
    response.raise_for_status()
    return response.json()["access_token"]


def search_track(query: str) -> str:
    """Search for a track and return 'Artist — Title' for the top hit."""
    response = requests.get(
        "https://api.spotify.com/v1/search",
        headers={"Authorization": f"Bearer {get_token()}"},
        params={"q": query, "type": "track", "limit": 1},
    )
    response.raise_for_status()
    item = response.json()["tracks"]["items"][0]
    return f"{item['artists'][0]['name']} — {item['name']}"


if __name__ == "__main__":
    print(search_track("Bohemian Rhapsody"))
