#!/usr/bin/env python3
"""
iTunes Search API service for neo-pod-desktop.
"""

import urllib.parse
from typing import Optional, Dict, Any

import requests


def search_itunes(artist: str, title: str, limit: int = 5) -> Optional[Dict[str, Any]]:
    """
    Search iTunes Store for track metadata.

    Args:
        artist: Artist name
        title: Track title
        limit: Max results to fetch (default 5)

    Returns:
        Dict with keys: title, artist, album, album_artist, genre, year,
        track_number, track_total, disc_number, disc_total, cover_url.
        Returns None on failure or no results.
    """
    try:
        term = " ".join(p for p in (artist, title) if p)
        if not term:
            return None
        quoted = urllib.parse.quote(term)
        url = f"https://itunes.apple.com/search?term={quoted}&entity=song&limit={limit}&country=US"
        resp = requests.get(url, timeout=10)
        resp.raise_for_status()
        data = resp.json()
        results = data.get("results", [])
        if not results:
            return None
        r = results[0]
        cover_url = r.get("artworkUrl100", "")
        if cover_url:
            cover_url = cover_url.replace("100x100", "600x600")
        year = 0
        release_date = r.get("releaseDate", "")
        if release_date and len(release_date) >= 4:
            try:
                year = int(release_date[:4])
            except (ValueError, TypeError):
                pass
        return {
            "title": r.get("trackName", ""),
            "artist": r.get("artistName", ""),
            "album": r.get("collectionName", ""),
            "album_artist": r.get("collectionArtistName", ""),
            "genre": r.get("primaryGenreName", ""),
            "year": year,
            "track_number": r.get("trackNumber", 0) or 0,
            "track_total": r.get("trackCount", 0) or 0,
            "disc_number": r.get("discNumber", 0) or 0,
            "disc_total": r.get("discCount", 0) or 0,
            "cover_url": cover_url,
        }
    except Exception:
        return None
