#! /usr/bin/env python3

import argparse
import sys
import subprocess
import logging
import spotipy
from pathlib import Path
from spotipy.oauth2 import SpotifyOAuth

logger = logging.getLogger(__name__)


def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(
        prog="spotify-current-track-id",
        description="Get the currently playing track ID from Spotify",
    )
    ap.add_argument(
        "--url",
        help="Print the URL of the currently playing track",
        action="store_true",
    )
    ap.add_argument(
        "-v", "--verbose", help="Enable verbose logging", action="store_true"
    )
    args = ap.parse_args()

    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(levelname)s:	%(message)s",
    )

    # Read API credentials from 1Password
    client_id = subprocess.check_output(
        "op read -n 'op://ewconfig/rio7e6skp6bhkkcdo5w3kmabgq/Client ID'", shell=True
    ).decode("utf-8")
    client_secret = subprocess.check_output(
        "op read -n 'op://ewconfig/rio7e6skp6bhkkcdo5w3kmabgq/credential'", shell=True
    ).decode("utf-8")

    # Connect to Spotify
    cache_path = Path("~/.cache/spotipy/spotify-current-track-id.oauth").expanduser()
    cache_path.parent.mkdir(parents=True, exist_ok=True)
    oauth = SpotifyOAuth(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri="http://localhost:8933",
        scope="user-read-currently-playing",
        cache_path=cache_path.as_posix(),
        open_browser=True,
    )
    spotify = spotipy.Spotify(auth_manager=oauth)

    # Read the currently playing track
    current_track = spotify.current_user_playing_track()

    # If nothing is playing
    if not current_track:
        print("Nothing is currently playing", file=sys.stderr)
        return 1

    # Display info
    if args.url:
        print(current_track["item"]["external_urls"]["spotify"])
    else:
        print(current_track["item"]["id"])

    return 0


if __name__ == "__main__":
    sys.exit(main())