import logging

import openfoodfacts

logger = logging.getLogger(__name__)

OFF_API = openfoodfacts.API(
    user_agent="Vrobbler/1.0 (https://github.com/powellc/vrobbler)",
    version=openfoodfacts.APIVersion.v2,
)


def search_products(query: str) -> list[dict]:
    if not query or not query.strip():
        return []

    try:
        results = OFF_API.product.text_search(query)
    except Exception:
        logger.exception("Open Food Facts search request failed")
        return []

    products = results.get("products", [])
    if not products:
        return []

    return [_normalize_product(p) for p in products]


def get_product(code: str) -> dict | None:
    try:
        product = OFF_API.product.get(code)
    except Exception:
        logger.exception("Open Food Facts product lookup failed")
        return None

    if not product:
        return None

    return _normalize_product(product)


def _normalize_product(product: dict) -> dict:
    nutriments = product.get("nutriments", {})
    categories = product.get("categories_tags", [])
    category_names = []
    for cat in categories:
        if cat.startswith("en:"):
            category_names.append(cat[3:].replace("-", " ").title())
        elif cat.startswith("fr:"):
            category_names.append(cat[3:].replace("-", " ").title())

    return {
        "code": product.get("code", ""),
        "product_name": product.get("product_name", product.get("product_name_en", "")),
        "brands": product.get("brands", ""),
        "categories": category_names,
        "ingredients_text": product.get(
            "ingredients_text_en", product.get("ingredients_text", "")
        ),
        "image_url": product.get("image_front_url", product.get("image_url", "")),
        "nutriments": {
            "calories": _safe_int(nutriments.get("energy-kcal_100g")),
            "protein": _safe_float(nutriments.get("proteins_100g")),
            "fat": _safe_float(nutriments.get("fat_100g")),
            "carbohydrates": _safe_float(nutriments.get("carbohydrates_100g")),
            "fiber": _safe_float(nutriments.get("fiber_100g")),
            "sugar": _safe_float(nutriments.get("sugars_100g")),
            "sodium": _safe_float(nutriments.get("sodium_100g")),
        },
        "serving_size": product.get("serving_size", ""),
    }


def _safe_int(value) -> int | None:
    if value is None:
        return None
    try:
        return int(value)
    except (ValueError, TypeError):
        return None


def _safe_float(value) -> float | None:
    if value is None:
        return None
    try:
        return float(value)
    except (ValueError, TypeError):
        return None
