"""
Spotify OAuth2 Handler for Luke.

Manages authorization, token refresh, and service access for Spotify.
Uses Authorization Code flow with spotipy's built-in redirect handling.

Redirect URI: http://127.0.0.1:8091
  → Spotify allows http for 127.0.0.1 (but NOT "localhost")
  → Add exactly this in Spotify Developer Dashboard > Settings > Redirect URIs

Scopes:
  - user-read-currently-playing: what's playing now
  - user-read-recently-played: recent listening history
  - user-read-playback-state: playback device info
  - user-modify-playback-state: play/pause/skip/queue
  - user-top-read: top artists and tracks
  - playlist-read-private: read private playlists
  - playlist-modify-public: create/edit playlists
  - playlist-modify-private: create/edit private playlists

Setup:
  1. Add SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET to ~/clawd/.env
  2. In Spotify Dashboard > Settings > Redirect URIs, add: http://127.0.0.1:8091
  3. Run: python3 setup_spotify_auth.py
  4. Authorize in browser
  5. Token auto-refreshes from there
"""

import os
import json
import logging
from pathlib import Path

logger = logging.getLogger("spotify-auth")

# Paths
CLAWD_DIR = Path.home() / "clawd"
TOKEN_PATH = CLAWD_DIR / ".spotify-token.json"

# Spotify app credentials
SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID", "")
SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET", "")

# IMPORTANT: Use 127.0.0.1, NOT localhost
# Spotify allows http:// for 127.0.0.1 but blocks http://localhost
SPOTIFY_REDIRECT_URI = "http://127.0.0.1:8091"

SCOPES = [
    "user-read-currently-playing",
    "user-read-recently-played",
    "user-read-playback-state",
    "user-modify-playback-state",
    "user-top-read",
    "user-follow-read",
    "playlist-read-private",
    "playlist-modify-public",
    "playlist-modify-private",
]


def is_configured():
    """Check if Spotify credentials are set."""
    return bool(SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET)


def get_spotify_client():
    """
    Get an authenticated Spotipy client.
    Returns None if not configured or token is missing.
    """
    if not is_configured():
        logger.info("Spotify not configured. Set SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET in .env")
        return None

    try:
        import spotipy
        from spotipy.oauth2 import SpotifyOAuth

        auth_manager = SpotifyOAuth(
            client_id=SPOTIFY_CLIENT_ID,
            client_secret=SPOTIFY_CLIENT_SECRET,
            redirect_uri=SPOTIFY_REDIRECT_URI,
            scope=" ".join(SCOPES),
            cache_path=str(TOKEN_PATH),
            open_browser=False,
        )

        # Check if we have a cached token
        token_info = auth_manager.get_cached_token()
        if not token_info:
            logger.warning("No Spotify token found. Run setup_spotify_auth.py first.")
            return None

        client = spotipy.Spotify(auth_manager=auth_manager)
        # Quick validation
        client.current_user()
        logger.info("Spotify client: ACTIVE")
        return client

    except Exception as e:
        logger.error(f"Spotify client init failed: {e}")
        return None


def get_auth_manager():
    """Get the SpotifyOAuth manager (used by setup script)."""
    import spotipy
    from spotipy.oauth2 import SpotifyOAuth

    return SpotifyOAuth(
        client_id=SPOTIFY_CLIENT_ID,
        client_secret=SPOTIFY_CLIENT_SECRET,
        redirect_uri=SPOTIFY_REDIRECT_URI,
        scope=" ".join(SCOPES),
        cache_path=str(TOKEN_PATH),
        open_browser=True,
    )
