"""
Central configuration for the Tabdeal Trading Bot.
All user-tunable parameters live here or in .env.
"""
import os
from dataclasses import dataclass, field
from typing import Optional
from dotenv import load_dotenv

load_dotenv()


@dataclass
class ExchangeConfig:
    api_key: str = field(default_factory=lambda: os.getenv("TABDEAL_API_KEY", ""))
    api_secret: str = field(default_factory=lambda: os.getenv("TABDEAL_API_SECRET", ""))
    base_url: str = "https://api1.tabdeal.org"
    recv_window: int = 5000
    # demo mode uses paper trading (no real orders sent)
    demo_mode: bool = field(default_factory=lambda: os.getenv("DEMO_MODE", "true").lower() == "true")


@dataclass
class TradingConfig:
    symbol: str = "BTCUSDT"           # futures symbol
    timeframe: str = "5m"             # candle timeframe
    leverage: int = 5
    initial_analysis_minutes: int = 5  # how long to observe before first trade

    # Risk per trade as a fraction of equity (0.01 = 1%)
    risk_per_trade: float = 0.01
    max_position_usdt: float = 1000.0

    # SL/TP as ATR multipliers
    sl_atr_multiplier: float = 1.5
    tp_atr_multiplier: float = 3.0     # gives ~1:2 R:R

    # Daily limits
    max_daily_loss_pct: float = 0.03   # 3% of balance
    max_drawdown_pct: float = 0.10     # 10% max drawdown → halt

    # Trailing stop
    trailing_stop_enabled: bool = True
    trailing_stop_atr_multiplier: float = 1.0

    # Adaptive direction logic
    reverse_on_loss: bool = True       # flip direction after a losing trade
    continue_on_win: bool = True       # keep direction after a winning trade

    # Minimum R:R to enter a trade
    min_risk_reward: float = 2.0

    # Fees (taker for futures)
    taker_fee: float = 0.0005          # 0.05%
    slippage: float = 0.0003           # 0.03% estimated slippage

    # Number of candles to look back for analysis
    lookback_candles: int = 100


@dataclass
class StrategyConfig:
    # EMA periods
    ema_fast: int = 20
    ema_slow: int = 50

    # ADX threshold to confirm trend (> threshold = trending)
    adx_threshold: float = 25.0

    # RSI thresholds
    rsi_period: int = 14
    rsi_overbought: float = 70.0
    rsi_oversold: float = 30.0

    # ATR period
    atr_period: int = 14

    # Volume: candle volume must be > this multiple of rolling average
    volume_multiplier: float = 1.0

    # Minimum ADX for signal to be valid
    min_adx: float = 20.0


@dataclass
class BotConfig:
    exchange: ExchangeConfig = field(default_factory=ExchangeConfig)
    trading: TradingConfig = field(default_factory=TradingConfig)
    strategy: StrategyConfig = field(default_factory=StrategyConfig)

    log_level: str = "INFO"
    log_file: str = "data/bot.log"
    trades_file: str = "data/trades.json"
    state_file: str = "data/state.json"

    # Polling interval in seconds when waiting for position to close
    poll_interval_seconds: int = 10


# Singleton
_config: Optional[BotConfig] = None


def get_config() -> BotConfig:
    global _config
    if _config is None:
        _config = BotConfig()
    return _config
