import asyncio
import json
from decimal import Decimal
from typing import AsyncIterator

import websockets

from .config import config
from .logger import get_logger


log = get_logger(__name__)


class DeltaWebSocket:
    """Light wrapper for future live streaming.

    The bot can run from REST ticker polling in Phase 1. This class keeps the
    WebSocket integration isolated so it can replace polling without changing
    the strategy or paper trade code.
    """

    def __init__(self, symbols: list[str]) -> None:
        self.symbols = symbols
        self.url = config.delta_ws_url

    async def ticks(self) -> AsyncIterator[tuple[str, Decimal]]:
        async with websockets.connect(self.url, ping_interval=20) as ws:
            await ws.send(
                json.dumps(
                    {
                        "type": "subscribe",
                        "payload": {
                            "channels": [
                                {"name": "v2/ticker", "symbols": self.symbols}
                            ]
                        },
                    }
                )
            )
            async for message in ws:
                data = json.loads(message)
                payload = data.get("payload") or data
                symbol = payload.get("symbol")
                price = payload.get("mark_price") or payload.get("close")
                if symbol and price:
                    yield symbol, Decimal(str(price))


async def consume_forever(symbols: list[str], callback) -> None:
    while True:
        try:
            async for symbol, price in DeltaWebSocket(symbols).ticks():
                await callback(symbol, price)
        except Exception:
            log.exception("WebSocket stream failed, reconnecting shortly")
            await asyncio.sleep(5)

