"""
Configuration for the Crypto Arbitrage Model.
"""
import os
from decimal import Decimal

# Trading pairs (canonical symbols)
SYMBOLS = ["BTC", "ETH", "SOL", "XRP", "DOGE"]

# Exchange roles
# Default: Global Binance. For US deployments, set BINANCE_ENDPOINT env var.
LEAD_EXCHANGE = "binance"
LAG_EXCHANGES = ["coinbase", "bybit", "okx"]

# WebSocket endpoints
# Note: Use BINANCE_ENDPOINT env var to override (e.g., for US users needing Binance US)
# Default is global Binance which works from most regions
_BINANCE_ENDPOINT = os.environ.get(
    "BINANCE_ENDPOINT",
    "wss://stream.binance.com:9443/ws"  # Global Binance (default)
)
# For US-based deployments, set BINANCE_ENDPOINT=wss://stream.binance.us:9443/ws
ENDPOINTS = {
    "binance": _BINANCE_ENDPOINT,
    "coinbase": "wss://ws-feed.exchange.coinbase.com",
    "bybit": "wss://stream.bybit.com/v5/public/spot",
    "okx": "wss://ws.okx.com:8443/ws/v5/public",
}

# Symbol mappings: canonical -> exchange-specific
SYMBOL_MAP = {
    "binance": {
        "BTC": "btcusdt",
        "ETH": "ethusdt",
        "SOL": "solusdt",
        "XRP": "xrpusdt",
        "DOGE": "dogeusdt",
    },
    "coinbase": {
        "BTC": "BTC-USD",
        "ETH": "ETH-USD",
        "SOL": "SOL-USD",
        "XRP": "XRP-USD",
        "DOGE": "DOGE-USD",
    },
    "bybit": {
        "BTC": "BTCUSDT",
        "ETH": "ETHUSDT",
        "SOL": "SOLUSDT",
        "XRP": "XRPUSDT",
        "DOGE": "DOGEUSDT",
    },
    "okx": {
        "BTC": "BTC-USDT",
        "ETH": "ETH-USDT",
        "SOL": "SOL-USDT",
        "XRP": "XRP-USDT",
        "DOGE": "DOGE-USDT",
    },
}

# Reverse mappings: exchange-specific -> canonical
REVERSE_SYMBOL_MAP = {
    exchange: {v: k for k, v in symbols.items()}
    for exchange, symbols in SYMBOL_MAP.items()
}

# Also add uppercase versions for Binance (messages come in uppercase)
REVERSE_SYMBOL_MAP["binance"].update({
    "BTCUSDT": "BTC",
    "ETHUSDT": "ETH",
    "SOLUSDT": "SOL",
    "XRPUSDT": "XRP",
    "DOGEUSDT": "DOGE",
})

# Taker fees (retail tiers)
FEES = {
    "binance": Decimal("0.001"),   # 0.1%
    "coinbase": Decimal("0.006"),  # 0.6%
    "bybit": Decimal("0.001"),     # 0.1%
    "okx": Decimal("0.001"),       # 0.1%
}

# Arbitrage settings
SPREAD_THRESHOLD_BPS = Decimal("20")  # 20 basis points minimum
STALE_TICK_MS = 500  # Ticks older than this are considered stale

# Reconnection settings
RECONNECT_BASE_DELAY_S = 1.0
RECONNECT_MAX_DELAY_S = 60.0
COINBASE_MIN_RECONNECT_INTERVAL_S = 60.0  # Coinbase rate limit

# Heartbeat intervals (seconds)
HEARTBEAT_INTERVALS = {
    "binance": None,  # Server handles pings
    "coinbase": None,  # No client ping needed
    "bybit": 20,
    "okx": 30,
}

# Paper trading settings
PAPER_TRADE_SIZE_USD = Decimal("1000")  # Hypothetical trade size
SUMMARY_INTERVAL_S = 60  # Print summary every N seconds

# =============================================================================
# Lead-Lag Model Settings
# =============================================================================
# Based on research: BTC leads altcoins by 16-118 seconds (avg 57s)
# References:
#   - arXiv:2109.10662 (Dynamic cointegration pairs trading)
#   - arXiv:2403.12180 (Statistical arbitrage with RL)
#   - research/lead_lag_analysis.md

# Rolling window sizes (in ticks, ~100ms each)
LEAD_LAG_STATS_WINDOW = 100          # Window for rolling mean/std
LEAD_LAG_BETA_WINDOW = 200           # Window for beta calculation

# Signal thresholds
# Leader Z threshold: Min |Z| for BTC move to trigger signal
# Based on standard practice: Z > 2 indicates significant move (95% CI)
LEAD_LAG_LEADER_Z_THRESHOLD = 2.0

# Lag Z threshold: Max |Z| for altcoin (if already moved, opportunity missed)
LEAD_LAG_LAG_Z_THRESHOLD = 1.0

# Minimum correlation to trust rolling beta (fallback to research values if lower)
LEAD_LAG_MIN_CORRELATION = 0.5

# Minimum confidence score to emit signal (0-1)
LEAD_LAG_MIN_CONFIDENCE = 0.6

# Return gap threshold: Signal when |expected - actual| > this × std
LEAD_LAG_GAP_THRESHOLD = 1.5

# Maximum lag window in milliseconds (based on research: 16-118s, use 60s)
LEAD_LAG_MAX_LAG_MS = 60_000

# Half-life multiplier for max hold time
LEAD_LAG_HALF_LIFE_MULTIPLIER = 2.0

# Default half-life if can't calculate (30 seconds)
LEAD_LAG_DEFAULT_HALF_LIFE_MS = 30_000

# Confidence decay rate per second (signal weakens over time)
LEAD_LAG_CONFIDENCE_DECAY_PER_SEC = 0.05

# Research-based beta coefficients (fallback values)
# Source: JamesBachini crypto beta analysis, lead_lag_analysis.md
RESEARCH_BETAS = {
    "ETH": 0.85,    # Lower beta, highly liquid
    "SOL": 1.98,    # ~2x BTC moves
    "XRP": 1.0,     # Roughly tracks BTC
    "DOGE": 1.5,    # More volatile
    "BNB": 1.34,    # Binance native
    "MATIC": 2.07,  # High beta
    "AVAX": 2.38,   # High beta
}

# Enable/disable lead-lag model (vs simple spread arbitrage)
ENABLE_LEAD_LAG_MODEL = True

# =============================================================================
# Live Execution Settings (Rust Order Manager)
# =============================================================================
# Execution mode: "paper" for simulation, "live" for real orders via Rust
EXECUTION_MODE = "paper"

# Rust order manager connection
RUST_ORDER_MANAGER_HOST = "127.0.0.1"
RUST_ORDER_MANAGER_PORT = 9999
RUST_ACK_PORT = 9998

# Position limits
MAX_POSITION_USD = Decimal("10000")
MAX_POSITIONS_PER_SYMBOL = 1
LIVE_TRADE_SIZE_USD = Decimal("100")  # Start small for live trading

# Exchange IDs for binary protocol
EXCHANGE_IDS = {
    "binance": 0,
    "coinbase": 1,
    "bybit": 2,
    "okx": 3,
}

# Signal staleness threshold (reject signals older than this)
SIGNAL_STALE_MS = 500

# =============================================================================
# Quantitative Model Settings
# =============================================================================
# These settings control the advanced financial models from the mathematical
# treatise: GARCH, VaR/ES, Regime Detection, Jump Detection, etc.

# -----------------------------------------------------------------------------
# Model Enable Flags
# -----------------------------------------------------------------------------
ENABLE_VOLATILITY_MODELS = True    # GARCH, EGARCH, Realized Volatility
ENABLE_RISK_MODELS = True          # VaR, CVaR/ES, EVT
ENABLE_REGIME_MODELS = True        # Hamilton Filter, MS-GARCH
ENABLE_JUMP_MODELS = True          # Lee-Mykland jump detection
ENABLE_KALMAN_MODELS = True        # Kalman filter hedge ratios
ENABLE_MICROSTRUCTURE_MODELS = True  # Kyle's lambda, price impact

# -----------------------------------------------------------------------------
# GARCH Model Settings
# -----------------------------------------------------------------------------
# GARCH(1,1): σₜ² = ω + α×εₜ₋₁² + β×σₜ₋₁²
# Crypto typical: α=0.05-0.15, β=0.85-0.94, persistence α+β→0.99

GARCH_ALPHA = 0.05              # ARCH coefficient (shock sensitivity)
GARCH_BETA = 0.94               # GARCH coefficient (persistence)
GARCH_WARMUP_TICKS = 200        # Ticks before stable estimates

# EGARCH asymmetry: γ > 0 for crypto (inverse leverage effect)
EGARCH_GAMMA = 0.05             # Asymmetry parameter

# Volatility spike threshold (multiple of long-run vol)
VOL_SPIKE_THRESHOLD = 3.0

# -----------------------------------------------------------------------------
# Risk Model Settings (VaR/ES)
# -----------------------------------------------------------------------------
# Crypto typical 99% daily VaR: -13% to -18%
# Crypto typical 99% ES: -20% to -27%

VAR_CONFIDENCE_LEVELS = [0.95, 0.99]  # Confidence levels for VaR/ES
VAR_HISTORY_SIZE = 1000               # Returns to store for historical VaR
STUDENT_T_DF = 5.0                    # Student-t degrees of freedom (crypto: 3-6)
VAR_WARMUP_TICKS = 500                # Ticks before stable VaR

# EVT (Extreme Value Theory) settings
EVT_THRESHOLD_QUANTILE = 0.95   # Quantile for POT threshold
EVT_WARMUP_TICKS = 1000         # Requires more data for tail estimation

# -----------------------------------------------------------------------------
# Regime Detection Settings
# -----------------------------------------------------------------------------
# Hamilton filter for Markov-switching models
# Crypto: Bull (μ≈0.09 daily, p₁₁≈0.98), Bear (μ<0, p₂₂≈0.95)

REGIME_COUNT = 2                # Number of regimes (2 or 3)
REGIME_WARMUP_TICKS = 500       # Ticks before regime detection

# Regime parameters (per-tick values, ~100ms ticks)
REGIME_BULL_MEAN = 0.0002       # Bull regime mean return
REGIME_BEAR_MEAN = -0.0001      # Bear regime mean return
REGIME_BULL_VOL = 0.001         # Bull regime volatility
REGIME_BEAR_VOL = 0.003         # Bear regime volatility
REGIME_PERSISTENCE_BULL = 0.98  # P(stay in bull)
REGIME_PERSISTENCE_BEAR = 0.95  # P(stay in bear)

# -----------------------------------------------------------------------------
# Jump Detection Settings
# -----------------------------------------------------------------------------
# Lee-Mykland test using bipower variation
# Crypto: ~3.5 jumps per day on 1-minute data

JUMP_WINDOW_SIZE = 100          # Window for bipower variation
JUMP_SIGNIFICANCE = 0.001       # Test significance level (conservative)
JUMP_WARMUP_TICKS = 200         # Ticks before jump testing

# -----------------------------------------------------------------------------
# Kalman Filter Settings
# -----------------------------------------------------------------------------
# State-space model for dynamic hedge ratios
# Outperforms rolling OLS for crypto due to structural breaks

KALMAN_Q_BETA = 0.0001          # Process noise for beta (higher = faster adapt)
KALMAN_Q_ALPHA = 0.00001        # Process noise for intercept
KALMAN_R = 0.0001               # Measurement noise (return variance proxy)
KALMAN_WARMUP_TICKS = 100       # Ticks before stable estimates

# -----------------------------------------------------------------------------
# Microstructure Model Settings
# -----------------------------------------------------------------------------
# Kyle's lambda, Amihud illiquidity, price impact estimation

KYLE_WINDOW_SIZE = 200          # Window for Kyle's lambda estimation
KYLE_WARMUP_TICKS = 200         # Ticks before stable estimate

# -----------------------------------------------------------------------------
# Black-Scholes Settings
# -----------------------------------------------------------------------------
# For implied vol estimation and Greeks calculation
# Crypto: IV ranges 20%-150% (vs equity 15%-25%)

BSM_RISK_FREE_RATE = 0.05       # Risk-free rate (annualized)
BSM_ETH_STAKING_YIELD = 0.035   # ETH staking yield (~3.5% annually)

# -----------------------------------------------------------------------------
# Model Signal Settings
# -----------------------------------------------------------------------------
# Rate limiting and signal emission parameters

MODEL_SIGNAL_COOLDOWN_MS = 1000  # Minimum ms between signals per model
MODEL_VOL_SPIKE_COOLDOWN_MS = 5000  # Cooldown for vol spike signals
MODEL_REGIME_CHANGE_COOLDOWN_MS = 10000  # Cooldown for regime changes
MODEL_JUMP_COOLDOWN_MS = 500     # Cooldown for jump signals
