"""
Normalized tick data model.
"""
from dataclasses import dataclass
from decimal import Decimal
import time


@dataclass(slots=True)
class Tick:
    """
    Normalized tick representing top-of-book data from any exchange.
    """
    exchange: str       # "binance", "coinbase", "bybit", "okx"
    symbol: str         # Canonical symbol: "BTC", "ETH", etc.
    bid: Decimal        # Best bid price
    ask: Decimal        # Best ask price
    bid_qty: Decimal    # Quantity at best bid
    ask_qty: Decimal    # Quantity at best ask
    exchange_ts: int    # Exchange timestamp in milliseconds
    local_ts: int       # Local receipt timestamp in milliseconds

    def is_stale(self, max_age_ms: int = 500) -> bool:
        """Check if this tick is older than max_age_ms."""
        now_ms = int(time.time() * 1000)
        return (now_ms - self.local_ts) > max_age_ms

    def mid_price(self) -> Decimal:
        """Calculate mid price."""
        return (self.bid + self.ask) / 2

    def spread_bps(self) -> Decimal:
        """Calculate bid-ask spread in basis points."""
        if self.bid == 0:
            return Decimal("0")
        return ((self.ask - self.bid) / self.bid) * 10000

    def __repr__(self) -> str:
        return (
            f"Tick({self.exchange}:{self.symbol} "
            f"bid={self.bid} ask={self.ask} "
            f"age={int(time.time() * 1000) - self.local_ts}ms)"
        )
