import httpx
from typing import List, Dict
from datetime import datetime
from app.config import settings
from app.schemas.schemas import PriceData


class AlphaVantageService:
    def __init__(self):
        self.base_url = settings.ALPHA_VANTAGE_BASE_URL
        self.api_key = settings.ALPHA_VANTAGE_API_KEY

    async def get_gold_daily_data(
        self, output_size: str = "compact"
    ) -> List[PriceData]:
        """
        Fetch daily gold price data from Alpha Vantage using GLD ETF
        GLD tracks gold prices closely (1 share ≈ 0.1 oz of gold)

        Args:
            output_size: 'compact' (100 data points) or 'full' (20+ years)

        Returns:
            List of PriceData objects
        """
        params = {
            "function": "TIME_SERIES_DAILY",
            "symbol": "GLD",
            "outputsize": output_size,
            "apikey": self.api_key,
        }

        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(self.base_url, params=params)
            response.raise_for_status()
            data = response.json()

        if "Time Series (Daily)" not in data:
            raise ValueError(f"Invalid API response: {data}")

        time_series = data["Time Series (Daily)"]
        price_data = []

        for date_str, values in time_series.items():
            # Convert date to Unix timestamp
            dt = datetime.strptime(date_str, "%Y-%m-%d")
            timestamp = int(dt.timestamp())

            price_data.append(
                PriceData(
                    time=timestamp,
                    open=float(values["1. open"]),
                    high=float(values["2. high"]),
                    low=float(values["3. low"]),
                    close=float(values["4. close"]),
                )
            )

        # Sort by time (oldest first)
        price_data.sort(key=lambda x: x.time)
        return price_data

    async def get_gold_intraday_data(
        self, interval: str = "15min", output_size: str = "compact"
    ) -> List[PriceData]:
        """
        Fetch intraday gold price data using GLD ETF

        Args:
            interval: '1min', '5min', '15min', '30min', '60min'
            output_size: 'compact' or 'full'

        Returns:
            List of PriceData objects
        """
        params = {
            "function": "TIME_SERIES_INTRADAY",
            "symbol": "GLD",
            "interval": interval,
            "outputsize": output_size,
            "apikey": self.api_key,
        }

        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(self.base_url, params=params)
            response.raise_for_status()
            data = response.json()

        time_series_key = f"Time Series ({interval})"
        if time_series_key not in data:
            raise ValueError(f"Invalid API response: {data}")

        time_series = data[time_series_key]
        price_data = []

        for datetime_str, values in time_series.items():
            dt = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
            timestamp = int(dt.timestamp())

            price_data.append(
                PriceData(
                    time=timestamp,
                    open=float(values["1. open"]),
                    high=float(values["2. high"]),
                    low=float(values["3. low"]),
                    close=float(values["4. close"]),
                )
            )

        price_data.sort(key=lambda x: x.time)
        return price_data

    async def get_current_gold_price(self) -> float:
        """Get current gold price using GLD ETF latest price"""
        params = {
            "function": "GLOBAL_QUOTE",
            "symbol": "GLD",
            "apikey": self.api_key,
        }

        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(self.base_url, params=params)
            response.raise_for_status()
            data = response.json()

        if "Global Quote" not in data:
            raise ValueError(f"Invalid API response: {data}")

        quote = data["Global Quote"]
        return float(quote["05. price"])


alpha_vantage_service = AlphaVantageService()
