import logging
import requests

logger = logging.getLogger(__name__)


def get_app_price(app_id):
    """Fetch price info from Steam Store API for a given app ID."""
    try:
        url = (
            f"https://store.steampowered.com/api/appdetails?appids={app_id}&cc=us&l=en"
        )
        headers = {"User-Agent": "Mozilla/5.0"}
        response = requests.get(url, headers=headers, timeout=10)

        if response.status_code == 200:
            data = response.json()
            app_data = data.get(str(app_id), {})
            if app_data.get("success"):
                info = app_data.get("data", {})
                if info.get("type") == "game":
                    price_data = info.get("price_overview", {})
                    if price_data:
                        return {
                            "name": info.get("name", ""),
                            "price": price_data.get("final_formatted", ""),
                            "price_raw": price_data.get("final", 0) / 100
                            if price_data.get("final")
                            else 0,
                            "discount": price_data.get("discount_percent", 0),
                            "currency": price_data.get("currency", "USD"),
                        }
                    elif info.get("is_free"):
                        return {
                            "name": info.get("name", ""),
                            "price": "Free",
                            "price_raw": 0,
                            "discount": 0,
                            "currency": "USD",
                        }
    except Exception as e:
        logger.debug(f"Failed to fetch price for {app_id}: {e}")

    return None


def get_app_prices_batch(app_ids):
    """Fetch prices for multiple app IDs."""
    results = {}
    for app_id in app_ids:
        price_info = get_app_price(app_id)
        if price_info:
            results[app_id] = price_info
    return results
