# ANVIL-MANAGED: true
# version: 1.4
# hash: 451fef11
# ---------------------------------------------------------
# AUTO-GENERATED BY ANVIL.
# To eject and take manual control, change 'ANVIL-MANAGED' to 'false'.
# ---------------------------------------------------------

import requests
import os
from typing import Dict, Any

def run(**kwargs) -> Dict[str, Any]:
    """
    Get the current stock price for NVIDIA (NVDA).
    
    Returns:
        Dict[str, Any]: Dictionary containing stock price data or error information
    """
    api_key = os.environ.get("ALPHA_VANTAGE_API_KEY")
    if not api_key:
        return {"error": "ALPHA_VANTAGE_API_KEY environment variable not set", "missing_credential": "ALPHA_VANTAGE_API_KEY"}
    
    symbol = "NVDA"
    url = f"https://www.alphavantage.co/query"
    
    params = {
        "function": "GLOBAL_QUOTE",
        "symbol": symbol,
        "apikey": api_key
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        
        if "Global Quote" in data:
            quote = data["Global Quote"]
            return {
                "symbol": quote.get("01. symbol", symbol),
                "price": float(quote.get("05. price", 0)),
                "change": float(quote.get("09. change", 0)),
                "change_percent": quote.get("10. change percent", "0%"),
                "last_updated": quote.get("07. latest trading day", "")
            }
        elif "Error Message" in data:
            return {"error": f"API Error: {data['Error Message']}"}
        elif "Note" in data:
            return {"error": f"API Limit: {data['Note']}"}
        else:
            return {"error": "Unexpected API response format"}
            
    except requests.exceptions.RequestException as e:
        return {"error": f"Request failed: {str(e)}"}
    except ValueError as e:
        return {"error": f"Failed to parse response: {str(e)}"}
    except Exception as e:
        return {"error": f"Unexpected error: {str(e)}"}