#!/usr/bin/env python3
"""
Configuration settings for the trading bot.

Loads settings from environment variables and config files.
"""

import os
from typing import List, Optional
from dataclasses import dataclass


@dataclass
class Settings:
    """Trading bot configuration settings."""
    
    # Trading symbols
    trading_symbols: List[str] = None
    
    # Markov chain parameters
    n_states: int = 10
    tau_threshold: float = 0.87
    eps_threshold: float = 0.05
    lookback_periods: int = 100
    
    # Kelly criterion parameters
    kelly_cap: float = 0.71
    safety_factor: float = 0.5
    min_win_rate: float = 0.55
    
    # Trading parameters
    paper_trading: bool = True
    initial_portfolio_value: float = 10000.0
    trading_interval_seconds: int = 60
    candle_timeframe: str = '1m'
    
    # Risk management
    max_position_pct: float = 0.90
    stop_loss_pct: float = 0.03
    
    # Exchange settings
    kraken_api_key: Optional[str] = None
    kraken_api_secret: Optional[str] = None
    
    # Database
    database_path: str = None
    
    def __post_init__(self):
        """Load settings from environment after initialization."""
        if self.trading_symbols is None:
            self.trading_symbols = self._load_symbols()
        
        if self.database_path is None:
            self.database_path = os.path.expanduser('~/bitcoin-bot/signals.db')
        
        # Load from environment
        self._load_from_env()
    
    def _load_symbols(self) -> List[str]:
        """Load trading symbols from environment or use defaults."""
        symbols = os.getenv('TRADING_SYMBOLS', 'XBT/USD')
        return [s.strip() for s in symbols.split(',')]
    
    def _load_from_env(self) -> None:
        """Load override values from environment variables."""
        if os.getenv('PAPER_TRADING'):
            self.paper_trading = os.getenv('PAPER_TRADING').lower() == 'true'
        
        if os.getenv('KRAKEN_API_KEY'):
            self.kraken_api_key = os.getenv('KRAKEN_API_KEY')
        
        if os.getenv('KRAKEN_API_SECRET'):
            self.kraken_api_secret = os.getenv('KRAKEN_API_SECRET')
        
        if os.getenv('INITIAL_PORTFOLIO_VALUE'):
            self.initial_portfolio_value = float(os.getenv('INITIAL_PORTFOLIO_VALUE'))
        
        if os.getenv('TAU_THRESHOLD'):
            self.tau_threshold = float(os.getenv('TAU_THRESHOLD'))
        
        if os.getenv('EPS_THRESHOLD'):
            self.eps_threshold = float(os.getenv('EPS_THRESHOLD'))
