#!/usr/bin/env python3
"""
One-time Spotify authorization for Luke.

Run this once:
  python3 setup_spotify_auth.py

It will open your browser to authorize with Spotify.
After you approve, paste the URL you get redirected to, and you're done.
"""

import sys
import os

# Load .env
from pathlib import Path
env_path = Path.home() / "clawd" / ".env"
if env_path.exists():
    from dotenv import load_dotenv
    load_dotenv(env_path)

from spotify_auth import is_configured, get_auth_manager, TOKEN_PATH, SPOTIFY_REDIRECT_URI


def main():
    print("\n  Spotify Setup for Luke")
    print("  " + "=" * 30)

    if not is_configured():
        print("\n  Missing credentials!")
        print("  Add these to ~/clawd/.env:")
        print("    SPOTIFY_CLIENT_ID=your_client_id")
        print("    SPOTIFY_CLIENT_SECRET=your_client_secret")
        print()
        sys.exit(1)

    print(f"\n  IMPORTANT: Make sure you added this redirect URI")
    print(f"  in Spotify Developer Dashboard > Settings > Redirect URIs:")
    print(f"    {SPOTIFY_REDIRECT_URI}")
    print(f"\n  (Use 127.0.0.1 — Spotify allows http for this IP)")
    print()

    auth_manager = get_auth_manager()
    auth_url = auth_manager.get_authorize_url()

    print("  Opening browser for Spotify authorization...")
    print(f"\n  If browser doesn't open, go to:")
    print(f"  {auth_url}\n")

    import webbrowser
    webbrowser.open(auth_url)

    print("  After approving, you'll be redirected to a URL starting with")
    print(f"  {SPOTIFY_REDIRECT_URI}?code=...")
    print()
    print("  Paste that full URL here:")
    redirect_url = input("  > ").strip()

    if not redirect_url:
        print("\n  No URL provided. Aborting.")
        sys.exit(1)

    try:
        code = auth_manager.parse_response_code(redirect_url)
        token_info = auth_manager.get_access_token(code)
    except Exception as e:
        print(f"\n  Error getting token: {e}")
        print("  Make sure you pasted the full URL including the ?code= part.")
        sys.exit(1)

    if token_info:
        print(f"\n  Authorized! Token saved to {TOKEN_PATH}")
        print("  Luke now has access to your Spotify.")

        # Quick test
        try:
            import spotipy
            sp = spotipy.Spotify(auth_manager=auth_manager)
            user = sp.current_user()
            print(f"  Connected as: {user['display_name']} ({user['id']})")
        except Exception as e:
            print(f"  (Couldn't verify account: {e})")

        print("\n  You're all set! Restart the agent to activate Spotify.")
    else:
        print("\n  Authorization failed. Try again.")
        sys.exit(1)


if __name__ == "__main__":
    main()
