#!/usr/bin/env python3

import sys
import tekore as tk
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)

try: 
	#tk.from_url(trackarg)
	#print("Looks like it's a track URL, we'll use that")
	track = spotify.track(tk.from_url(trackarg)[1])
except:
	#print("Looks like it's not a URL, maybe it's a URI?")
	try: 
		track = spotify.track(trackarg)
	except:
		print("Still failed?!?")
#trackid = tk.from_url(trackarg)[1]
#track = spotify.track(trackid)
#print(track.asbuiltin())
track_id = track.asbuiltin()['id']

available_markets = track.asbuiltin()['available_markets']

# Get the ISRC code to check for duplicate tracks that will be substituted automatically by Spotify if the submitted version isn't available in a jurisdiction
isrc = track.asbuiltin()['external_ids']['isrc']

# Now check for those additional versions, and append them to the available_markets array. I might be doing this in a reasonable way now?
search_results = spotify.search('isrc:{}'.format(isrc), types=('track',))
for p in search_results:
	for i in p.items:
		available_markets += i.asbuiltin()['available_markets']

# Not necessarily good enough, though! Lets check each of our preferred markets, sadly using a new API call for each (hence just a manual list for now) and seeing if there's any redirects
# Further reading: https://developer.spotify.com/documentation/general/guides/track-relinking-guide/
markets = ['AU', 'CA', 'IE', 'NL', 'NZ', 'US']
for m in markets:
	local_track = spotify.track(track_id, m)
	if local_track.asbuiltin()['is_playable'] is True:
		available_markets.append(m)

# Clear out duplicates
available_markets = list(dict.fromkeys(available_markets))
# Order it
available_markets.sort()


print(available_markets)
