import os
import sys
import webbrowser
import requests
import urllib.parse
from http.server import HTTPServer, BaseHTTPRequestHandler

# Instructions for the user:
# 1. Go to Spotify Developer Dashboard: https://developer.spotify.com/dashboard/
# 2. Create an App.
# 3. Edit Settings -> Redirect URIs -> Add "http://localhost:8888/callback"
# 4. Save Settings.
# 5. Copy Client ID and Client Secret.
# 6. Run this script: python get_refresh_token.py

# CONFIGURATION - You can hardcode these or input them when prompted
SPOTIFY_CLIENT_ID = input("Enter your Spotify Client ID: ").strip()
SPOTIFY_CLIENT_SECRET = input("Enter your Spotify Client Secret: ").strip()
REDIRECT_URI = "http://localhost:8888/callback"
SCOPE = "user-read-recently-played user-read-playback-state"

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        query = urllib.parse.urlparse(self.path).query
        params = urllib.parse.parse_qs(query)

        if "code" in params:
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(b"<h1>Got the code! check your terminal.</h1>")

            code = params["code"][0]
            get_token(code)

            # Shut down server
            raise KeyboardInterrupt

def get_token(code):
    url = "https://accounts.spotify.com/api/token"
    payload = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": REDIRECT_URI,
        "client_id": SPOTIFY_CLIENT_ID,
        "client_secret": SPOTIFY_CLIENT_SECRET,
    }

    response = requests.post(url, data=payload)
    if response.status_code == 200:
        data = response.json()
        print("\n" + "="*50)
        print("SUCCESS! HERE ARE YOUR CREDENTIALS")
        print("="*50)
        print(f"\nSPOTIFY_REFRESH_TOKEN={data['refresh_token']}")
        print(f"SPOTIFY_CLIENT_ID={SPOTIFY_CLIENT_ID}")
        print(f"SPOTIFY_CLIENT_SECRET={SPOTIFY_CLIENT_SECRET}")
        print("\nSave these in your .env file or share them with the agent.")
        print("="*50 + "\n")
    else:
        print("Error getting token:", response.text)

def start_auth():
    auth_url = "https://accounts.spotify.com/authorize?" + urllib.parse.urlencode({
        "response_type": "code",
        "client_id": SPOTIFY_CLIENT_ID,
        "scope": SCOPE,
        "redirect_uri": REDIRECT_URI,
    })

    print(f"Opening browser to: {auth_url}")
    try:
        webbrowser.open(auth_url)
    except:
        print(f"Could not open browser. Please manually visit: {auth_url}")

    server_address = ('', 8888)
    httpd = HTTPServer(server_address, RequestHandler)
    print("Listening on port 8888...")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()

if __name__ == "__main__":
    start_auth()
