import os

import httpx


async def handler(params: dict) -> dict:
    """Handle Spotify API operations."""
    action = params["action"]

    # Check for required credentials
    client_id = os.environ.get("SPOTIFY_CLIENT_ID")
    client_secret = os.environ.get("SPOTIFY_CLIENT_SECRET")
    access_token = os.environ.get("SPOTIFY_ACCESS_TOKEN")

    if not all([client_id, client_secret, access_token]):
        return {
            "success": False,
            "message": "Missing Spotify credentials. Set SPOTIFY_CLIENT_ID, "
            "SPOTIFY_CLIENT_SECRET, and SPOTIFY_ACCESS_TOKEN environment variables.",
            "data": {}
        }

    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }

    try:
        async with httpx.AsyncClient(timeout=30) as client:
            if action == "create_playlist":
                return await create_playlist(client, headers, params)
            elif action == "search_tracks":
                return await search_tracks(client, headers, params)
            elif action == "add_tracks_to_playlist":
                return await add_tracks_to_playlist(client, headers, params)
            else:
                return {
                    "success": False,
                    "message": f"Unknown action: {action}",
                    "data": {}
                }
    except httpx.HTTPStatusError as e:
        error_msg = f"Spotify API error: {e.response.status_code}"
        try:
            error_data = e.response.json()
            if "error" in error_data:
                error_msg += f" - {error_data['error'].get('message', 'Unknown error')}"
        except Exception:
            pass
        return {
            "success": False,
            "message": error_msg,
            "data": {}
        }
    except Exception as e:
        return {
            "success": False,
            "message": f"Error: {str(e)}",
            "data": {}
        }


async def create_playlist(client: httpx.AsyncClient, headers: dict, params: dict) -> dict:
    """Create a new Spotify playlist."""
    # First get current user ID
    user_resp = await client.get("https://api.spotify.com/v1/me", headers=headers)
    user_resp.raise_for_status()
    user_id = user_resp.json()["id"]

    # Create playlist
    playlist_data = {
        "name": params["name"],
        "description": params.get("description", ""),
        "public": params.get("public", False)
    }

    resp = await client.post(
        f"https://api.spotify.com/v1/users/{user_id}/playlists",
        headers=headers,
        json=playlist_data
    )
    resp.raise_for_status()

    playlist = resp.json()
    return {
        "success": True,
        "message": f"Created playlist '{playlist['name']}'",
        "data": {
            "id": playlist["id"],
            "name": playlist["name"],
            "url": playlist["external_urls"]["spotify"]
        }
    }


async def search_tracks(client: httpx.AsyncClient, headers: dict, params: dict) -> dict:
    """Search for tracks on Spotify."""
    query = params["query"]
    limit = min(params.get("limit", 10), 50)

    search_params = {
        "q": query,
        "type": "track",
        "limit": limit
    }

    resp = await client.get(
        "https://api.spotify.com/v1/search",
        headers=headers,
        params=search_params
    )
    resp.raise_for_status()

    data = resp.json()
    tracks = []

    for track in data["tracks"]["items"]:
        artists = ", ".join([artist["name"] for artist in track["artists"]])
        tracks.append({
            "name": track["name"],
            "artist": artists,
            "album": track["album"]["name"],
            "uri": track["uri"],
            "id": track["id"],
            "preview_url": track.get("preview_url")
        })

    return {
        "success": True,
        "message": f"Found {len(tracks)} tracks",
        "data": {"tracks": tracks}
    }


async def add_tracks_to_playlist(client: httpx.AsyncClient, headers: dict, params: dict) -> dict:
    """Add tracks to a Spotify playlist."""
    playlist_id = params["playlist_id"]
    track_uris = params["track_uris"]

    # Add tracks in batches of 100 (Spotify API limit)
    batch_size = 100
    added_count = 0

    for i in range(0, len(track_uris), batch_size):
        batch = track_uris[i:i + batch_size]

        resp = await client.post(
            f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks",
            headers=headers,
            json={"uris": batch}
        )
        resp.raise_for_status()
        added_count += len(batch)

    return {
        "success": True,
        "message": f"Added {added_count} tracks to playlist",
        "data": {"added_count": added_count}
    }
