import base64
import json
import requests

def get_access_token():
    # Load secrets from file
    with open("secrets.json") as f:
        secrets = json.load(f)

    client_id = secrets["client_id"]
    client_secret = secrets["client_secret"]

    # Encode client_id:client_secret as base64
    auth_str = f"{client_id}:{client_secret}"
    b64_auth_str = base64.b64encode(auth_str.encode()).decode()

    # Request access token
    response = requests.post(
        "https://accounts.spotify.com/api/token",
        headers={"Authorization": f"Basic {b64_auth_str}"},
        data={"grant_type": "client_credentials"},
    )

    if response.status_code != 200:
        raise Exception(f"Error: {response.status_code} - {response.text}")

    token_info = response.json()
    print("Access token:", token_info["access_token"])
    print("Expires in:", token_info["expires_in"], "seconds")

    return token_info["access_token"]

if __name__ == "__main__":
    token = get_access_token()
