"""Fear & Greed Index from alternative.me API."""

import logging
import requests

log = logging.getLogger(__name__)

FNG_URL = "https://api.alternative.me/fng/?limit=30"


def fetch():
    """Fetch Fear & Greed data. Returns dict with value, classification, and recent history."""
    try:
        resp = requests.get(FNG_URL, timeout=15)
        resp.raise_for_status()
        data = resp.json()
        entries = data.get("data", [])
        if not entries:
            return {"value": None, "error": "No data"}

        current = entries[0]
        value = int(current["value"])
        classification = current.get("value_classification", "")

        recent = [int(e["value"]) for e in entries[:30]]

        return {
            "value": value,
            "classification": classification,
            "recent": recent,
        }
    except Exception as e:
        log.error("Fear & Greed fetch error: %s", e)
        return {"value": None, "error": str(e)}
