from __future__ import annotations

from typing import List, Optional

import httpx

from app.schemas.schemas import PriceData

YAHOO_QUOTE_URL = "https://query1.finance.yahoo.com/v7/finance/quote"
YAHOO_CHART_URL = "https://query1.finance.yahoo.com/v8/finance/chart/{symbol}"
YAHOO_SYMBOL = "XAUUSD=X"
YAHOO_HEADERS = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0 Safari/537.36",
    "Accept": "application/json",
}


async def fetch_yahoo_quote(symbol: str = YAHOO_SYMBOL) -> Optional[dict]:
    params = {"symbols": symbol}
    async with httpx.AsyncClient(timeout=20.0, headers=YAHOO_HEADERS) as client:
        response = await client.get(YAHOO_QUOTE_URL, params=params)
        response.raise_for_status()
        data = response.json()
    result = (data.get("quoteResponse", {}) or {}).get("result", [])
    if not result:
        return None
    quote = result[0]
    def _safe_float(value: Optional[float], default: float = 0.0) -> float:
        try:
            return float(value)
        except (TypeError, ValueError):
            return default

    return {
        "symbol": symbol,
        "price": _safe_float(quote.get("regularMarketPrice"), default=0.0),
        "high": _safe_float(quote.get("regularMarketDayHigh")),
        "low": _safe_float(quote.get("regularMarketDayLow")),
        "volume": _safe_float(quote.get("regularMarketVolume"), default=0.0),
        "previous_close": _safe_float(quote.get("regularMarketPreviousClose"), default=0.0),
        "timestamp": int(quote.get("regularMarketTime") or 0),
    }


def _interval_range_for_chart(interval: str) -> tuple[str, str]:
    normalized = interval.lower()
    mapping = {
        "1m": ("1m", "1d"),
        "1min": ("1m", "1d"),
        "5m": ("5m", "5d"),
        "5min": ("5m", "5d"),
        "15m": ("15m", "1mo"),
        "15min": ("15m", "1mo"),
        "30m": ("30m", "1mo"),
        "30min": ("30m", "1mo"),
        "60m": ("60m", "1y"),
        "60min": ("60m", "1y"),
        "daily": ("1d", "5y"),
    }
    return mapping.get(normalized, ("1m", "1d"))


async def fetch_yahoo_ohlcv(symbol: str = YAHOO_SYMBOL, interval: str = "1m") -> List[PriceData]:
    interval_key, range_key = _interval_range_for_chart(interval)
    url = YAHOO_CHART_URL.format(symbol=symbol)
    params = {"interval": interval_key, "range": range_key, "includePrePost": "false"}
    async with httpx.AsyncClient(timeout=20.0, headers=YAHOO_HEADERS) as client:
        response = await client.get(url, params=params)
        response.raise_for_status()
        data = response.json()
    chart = (data.get("chart") or {}).get("result") or []
    if not chart:
        return []
    result = chart[0]
    timestamps = result.get("timestamp") or []
    indicators = (result.get("indicators") or {}).get("quote") or []
    if not indicators:
        return []
    quote = indicators[0]
    opens = quote.get("open") or []
    highs = quote.get("high") or []
    lows = quote.get("low") or []
    closes = quote.get("close") or []
    volumes = quote.get("volume") or []

    price_data: List[PriceData] = []
    for idx, ts in enumerate(timestamps):
        open_price = opens[idx] if idx < len(opens) else None
        high_price = highs[idx] if idx < len(highs) else None
        low_price = lows[idx] if idx < len(lows) else None
        close_price = closes[idx] if idx < len(closes) else None
        if None in (open_price, high_price, low_price, close_price):
            continue
        volume_val = volumes[idx] if idx < len(volumes) else 0.0
        price_data.append(
            PriceData(
                time=int(ts),
                open=float(open_price),
                high=float(high_price),
                low=float(low_price),
                close=float(close_price),
                volume=float(volume_val or 0.0),
            )
        )
    return price_data
