from __future__ import annotations

import asyncio
from datetime import datetime
from typing import AsyncIterator
import httpx

from ..typing import Kline
from app.config import settings


ALPHA_BASE = "https://www.alphavantage.co/query"


class AlphaVantageXAUProvider:
    def __init__(self, api_key: str | None = None):
        self.api_key = api_key or settings.alpha_vantage_api_key

    async def stream_klines(self, symbol: str, timeframe: str) -> AsyncIterator[Kline]:
        # Poll once per minute due to AV rate limits
        assert symbol.upper() in {"XAUUSD", "XAU/USD"}
        from_symbol = "XAU"
        to_symbol = "USD"
        interval = "1min" if timeframe == "1m" else "5min"
        async with httpx.AsyncClient(timeout=30) as client:
            while True:
                params = {
                    "function": "FX_INTRADAY",
                    "from_symbol": from_symbol,
                    "to_symbol": to_symbol,
                    "interval": interval,
                    "outputsize": "compact",
                    "apikey": self.api_key or "demo",
                }
                try:
                    r = await client.get(ALPHA_BASE, params=params)
                    r.raise_for_status()
                    js = r.json()
                    # Pick the latest candle
                    key = f"Time Series FX ({interval})"
                    series = js.get(key) or {}
                    if series:
                        ts, row = next(iter(series.items()))
                        dt = datetime.fromisoformat(ts)
                        yield Kline(
                            symbol="XAUUSD",
                            timeframe=timeframe,
                            open_time=dt,
                            close_time=dt,
                            open=float(row["1. open"]),
                            high=float(row["2. high"]),
                            low=float(row["3. low"]),
                            close=float(row["4. close"]),
                            volume=float(row.get("5. volume", 0.0)),
                            is_closed=True,
                            source="alpha_vantage",
                        )
                except Exception:
                    pass
                await asyncio.sleep(60)
