#!/usr/bin/env python3

import sys
import json
import tekore as tk
import libmusicleague
import pyml_config as config

# Set up Spotify connection using client token
conf = (config.client_id, config.client_secret)
token = tk.request_client_token(*conf)
spotify = tk.Spotify(token)

# Get track ID from first argument
trackarg = sys.argv[1]
print(trackarg)

# Determine the type of whatever was 
t = libmusicleague.ur_type(trackarg)
print(f"Determined type to be {t}")
try:
	match t:
		case "uri":
			track = spotify.track(trackarg.split(":")[-1])
		case "url":
			track = spotify.track(tk.from_url(trackarg)[1])
		case "new":
			n = libmusicleague.newurl_expand(trackarg)
			track = spotify.track(tk.from_url(n))
		case _:
			sys.exit("Not a valid Spotify URL or URI?")
except Exception as e:
	print("Something unexpected went wrong, check that you're using a valid Spotify link? Detailed error message follows in case that's not the and you need to bug Keith to fix something:")
	print(e)

#trackid = tk.from_url(trackarg)[1]
#track = spotify.track(trackid)
#print(track.asbuiltin())

json_object = json.loads(track.json())
#json_pretty = json.dumps(json_object, indent="\t", separators=(',', ':'))
json_pretty = json.dumps(json_object, cls=libmusicleague.CompactJSONEncoder)
# json_pretty = json.dumps(json_object, indent=0)
print(json_pretty)
