"""
Legacy HTTP API client for MusicBrainz Data Cleaner.
Used as fallback when direct database access is not available.
"""

import requests
import time
from typing import Dict, Optional, Any
from ..config.constants import (
    DEFAULT_MUSICBRAINZ_URL, API_REQUEST_DELAY, REQUEST_TIMEOUT,
    SUCCESS_MESSAGES, ERROR_MESSAGES
)


class MusicBrainzAPIClient:
    """Legacy HTTP API client for MusicBrainz (fallback option)."""
    
    def __init__(self, base_url: str = DEFAULT_MUSICBRAINZ_URL):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.timeout = REQUEST_TIMEOUT
    
    def test_connection(self) -> bool:
        """Test connection to MusicBrainz API server."""
        try:
            response = self.session.get(f"{self.base_url}/ws/2/artist/?query=name:test&fmt=json")
            response.raise_for_status()
            return True
        except Exception as e:
            print(f"API connection test failed: {e}")
            return False
    
    def search_artist(self, artist_name: str) -> Optional[Dict[str, Any]]:
        """Search for artist by name using API."""
        try:
            url = f"{self.base_url}/ws/2/artist/?query=name:{artist_name}&fmt=json"
            response = self.session.get(url)
            response.raise_for_status()
            data = response.json()
            
            if data.get('artists') and len(data['artists']) > 0:
                return data['artists'][0]
            return None
        except Exception as e:
            print(f"API search failed for artist '{artist_name}': {e}")
            return None
    
    def search_recording(self, title: str, artist_mbid: Optional[str] = None) -> Optional[Dict[str, Any]]:
        """Search for recording by title and optionally artist using API."""
        try:
            if artist_mbid:
                url = f"{self.base_url}/ws/2/recording/?query=arid:{artist_mbid}%20AND%20name:{title}&fmt=json"
            else:
                url = f"{self.base_url}/ws/2/recording/?query=name:{title}&fmt=json"
            
            response = self.session.get(url)
            response.raise_for_status()
            data = response.json()
            
            if data.get('recordings') and len(data['recordings']) > 0:
                return data['recordings'][0]
            return None
        except Exception as e:
            print(f"API search failed for recording '{title}': {e}")
            return None
    
    def get_artist_info(self, mbid: str) -> Optional[Dict[str, Any]]:
        """Get detailed artist information by MBID using API."""
        try:
            url = f"{self.base_url}/ws/2/artist/{mbid}?fmt=json"
            response = self.session.get(url)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"API get artist info failed for MBID '{mbid}': {e}")
            return None
    
    def get_recording_info(self, mbid: str) -> Optional[Dict[str, Any]]:
        """Get detailed recording information by MBID using API."""
        try:
            url = f"{self.base_url}/ws/2/recording/{mbid}?fmt=json&inc=artist-credits"
            response = self.session.get(url)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"API get recording info failed for MBID '{mbid}': {e}")
            return None 