import logging
import ssl
import requests
import urllib3
from requests.adapters import HTTPAdapter
from urllib3.util.ssl_ import create_urllib3_context

logger = logging.getLogger(__name__)

BASE_URL = "https://hubcapmanifest.com/api/v1"


class SSLAdapter(HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        ctx = create_urllib3_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        try:
            ctx.set_ciphers("DEFAULT:@SECLEVEL=1")
        except ssl.SSLError:
            pass
        kwargs["ssl_context"] = ctx
        return super().init_poolmanager(*args, **kwargs)


_session = requests.Session()
_session.verify = False
_session.mount("https://", SSLAdapter())
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

API_ERROR_MESSAGES = {
    401: "Invalid or missing API key. Please check your credentials.",
    403: "Access denied. Your account may be blocked.",
    404: "Game not found in library.",
    429: "Daily API limit exceeded. Please try again later.",
    500: "Server error. The manifest may be corrupted or temporarily unavailable.",
}


def _handle_api_error(response):
    status_code = response.status_code
    if status_code in API_ERROR_MESSAGES:
        error_msg = API_ERROR_MESSAGES[status_code]
        logger.error(f"API error ({status_code}): {error_msg}")
        return error_msg
    return None


def search_games(query, api_key):
    if not api_key:
        return {"error": "API Key is not set. Please set it in Settings."}

    headers = {"Authorization": f"Bearer {api_key}"}
    params = {"q": query, "limit": 50}
    url = f"{BASE_URL}/search"
    logger.info(f"Searching Hubcap API: {url} with query: {query}")

    try:
        response = _session.get(url, headers=headers, params=params, timeout=10)
        error_msg = _handle_api_error(response)
        if error_msg:
            return {"error": error_msg}
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        response = e.response
        response_text = response.text if response is not None else ""
        status_code = response.status_code if response is not None else "N/A"
        logger.error(f"API search HTTP error: {e} - {response_text}")
        try:
            if response is None:
                return {"error": f"API Error ({status_code}): {e}"}
            error_detail = response.json().get("detail", response_text)
            return {"error": f"API Error ({status_code}): {error_detail}"}
        except requests.exceptions.JSONDecodeError:
            return {"error": f"API Error ({status_code}): {response_text}"}
    except requests.exceptions.RequestException as e:
        logger.error(f"API search failed: {e}")
        error_str = str(e).lower()
        if "ssl" in error_str or "wrong_version_number" in error_str:
            return {"error": "SSL connection failed. Check proxy/firewall settings."}
        return {"error": f"Request Failed: {e}"}
    except Exception as e:
        logger.error(f"An unexpected error occurred during search: {e}", exc_info=True)
        return {"error": f"An unexpected error occurred: {e}"}
