//! Data provider endpoint configuration
//!
//! Centralizes all hardcoded API endpoints for data providers, enabling
//! environment-specific configurations and easy switching between dev/staging/prod.

use serde::{Deserialize, Serialize};

/// Environment specification for data providers
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DataProviderEnvironment {
    /// Development environment with potentially mocked or sandbox endpoints
    Development,
    /// Staging environment for pre-production testing
    Staging,
    /// Production environment with live data
    Production,
}

impl DataProviderEnvironment {
    /// Detect environment from FOXHUNT_ENV environment variable
    pub fn from_env() -> Self {
        match std::env::var("FOXHUNT_ENV")
            .unwrap_or_else(|_| "development".to_owned())
            .to_lowercase()
            .as_str()
        {
            "prod" | "production" => Self::Production,
            "staging" | "stage" => Self::Staging,
            _ => Self::Development,
        }
    }
}

/// Databento endpoint configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabentoEndpoints {
    /// WebSocket URL for real-time data streaming
    pub websocket_url: String,
    /// HTTP base URL for historical data queries
    pub historical_base_url: String,
}

impl DatabentoEndpoints {
    /// Create configuration from environment variables with fallback to defaults
    pub fn from_env(environment: DataProviderEnvironment) -> Self {
        let (ws_default, http_default) = match environment {
            DataProviderEnvironment::Development | DataProviderEnvironment::Production => (
                "wss://gateway.databento.com/v0/subscribe",
                "https://hist.databento.com",
            ),
            DataProviderEnvironment::Staging => (
                "wss://staging-gateway.databento.com/v0/subscribe",
                "https://staging-hist.databento.com",
            ),
        };

        Self {
            websocket_url: std::env::var("DATABENTO_WS_URL")
                .unwrap_or_else(|_| ws_default.to_owned()),
            historical_base_url: std::env::var("DATABENTO_HTTP_URL")
                .unwrap_or_else(|_| http_default.to_owned()),
        }
    }
}

impl Default for DatabentoEndpoints {
    fn default() -> Self {
        Self::from_env(DataProviderEnvironment::from_env())
    }
}

/// Benzinga endpoint configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenzingaEndpoints {
    /// WebSocket URL for real-time news and sentiment streaming
    pub websocket_url: String,
    /// HTTP base URL for API queries
    pub api_base_url: String,
}

impl BenzingaEndpoints {
    /// Create configuration from environment variables with fallback to defaults
    pub fn from_env(environment: DataProviderEnvironment) -> Self {
        let (ws_default, api_default) = match environment {
            DataProviderEnvironment::Development | DataProviderEnvironment::Production => (
                "wss://api.benzinga.com/api/v1/stream",
                "https://api.benzinga.com/api/v2",
            ),
            DataProviderEnvironment::Staging => (
                "wss://staging-api.benzinga.com/api/v1/stream",
                "https://staging-api.benzinga.com/api/v2",
            ),
        };

        Self {
            websocket_url: std::env::var("BENZINGA_WS_URL")
                .unwrap_or_else(|_| ws_default.to_owned()),
            api_base_url: std::env::var("BENZINGA_API_URL")
                .unwrap_or_else(|_| api_default.to_owned()),
        }
    }
}

impl Default for BenzingaEndpoints {
    fn default() -> Self {
        Self::from_env(DataProviderEnvironment::from_env())
    }
}

/// Alpaca endpoint configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlpacaEndpoints {
    /// Base URL for trading operations (paper or live)
    pub trading_base_url: String,
    /// Base URL for market data queries
    pub data_base_url: String,
}

impl AlpacaEndpoints {
    /// Create configuration from environment variables with fallback to defaults
    pub fn from_env(environment: DataProviderEnvironment) -> Self {
        let (trading_default, data_default) = match environment {
            DataProviderEnvironment::Development => (
                "https://paper-api.alpaca.markets",
                "https://data.alpaca.markets",
            ),
            DataProviderEnvironment::Staging => (
                "https://paper-api.alpaca.markets",
                "https://data.alpaca.markets",
            ),
            DataProviderEnvironment::Production => {
                ("https://api.alpaca.markets", "https://data.alpaca.markets")
            }
        };

        Self {
            trading_base_url: std::env::var("ALPACA_TRADING_URL")
                .unwrap_or_else(|_| trading_default.to_owned()),
            data_base_url: std::env::var("ALPACA_DATA_URL")
                .unwrap_or_else(|_| data_default.to_owned()),
        }
    }
}

impl Default for AlpacaEndpoints {
    fn default() -> Self {
        Self::from_env(DataProviderEnvironment::from_env())
    }
}

/// Interactive Brokers Gateway configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IBGatewayConfig {
    /// Gateway host (typically localhost for local TWS/Gateway)
    pub host: String,
    /// Gateway port (7497 for paper trading, 7496 for live, 4001 for IB Gateway)
    pub port: u16,
}

impl IBGatewayConfig {
    /// Create configuration from environment variables with fallback to defaults
    pub fn from_env(environment: DataProviderEnvironment) -> Self {
        let (host_default, port_default) = match environment {
            DataProviderEnvironment::Development => ("127.0.0.1", 7497), // Paper trading
            DataProviderEnvironment::Staging => ("127.0.0.1", 7497),     // Paper trading
            DataProviderEnvironment::Production => ("127.0.0.1", 7496),  // Live trading
        };

        Self {
            host: std::env::var("IB_GATEWAY_HOST").unwrap_or_else(|_| host_default.to_owned()),
            port: std::env::var("IB_GATEWAY_PORT")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(port_default),
        }
    }
}

impl Default for IBGatewayConfig {
    fn default() -> Self {
        Self::from_env(DataProviderEnvironment::from_env())
    }
}

/// Master configuration for all data provider endpoints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataProviderConfig {
    /// Current environment
    pub environment: DataProviderEnvironment,
    /// Databento endpoints
    pub databento: DatabentoEndpoints,
    /// Benzinga endpoints
    pub benzinga: BenzingaEndpoints,
    /// Alpaca endpoints
    pub alpaca: AlpacaEndpoints,
    /// Interactive Brokers Gateway configuration
    pub ib_gateway: IBGatewayConfig,
}

impl DataProviderConfig {
    /// Create configuration from environment
    pub fn from_env() -> Self {
        let environment = DataProviderEnvironment::from_env();
        Self {
            databento: DatabentoEndpoints::from_env(environment),
            benzinga: BenzingaEndpoints::from_env(environment),
            alpaca: AlpacaEndpoints::from_env(environment),
            ib_gateway: IBGatewayConfig::from_env(environment),
            environment,
        }
    }

    /// Create configuration for specific environment
    pub fn for_environment(environment: DataProviderEnvironment) -> Self {
        Self {
            databento: DatabentoEndpoints::from_env(environment),
            benzinga: BenzingaEndpoints::from_env(environment),
            alpaca: AlpacaEndpoints::from_env(environment),
            ib_gateway: IBGatewayConfig::from_env(environment),
            environment,
        }
    }
}

impl Default for DataProviderConfig {
    fn default() -> Self {
        Self::from_env()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_environment_detection() {
        std::env::set_var("FOXHUNT_ENV", "production");
        assert_eq!(
            DataProviderEnvironment::from_env(),
            DataProviderEnvironment::Production
        );

        std::env::set_var("FOXHUNT_ENV", "staging");
        assert_eq!(
            DataProviderEnvironment::from_env(),
            DataProviderEnvironment::Staging
        );

        std::env::set_var("FOXHUNT_ENV", "development");
        assert_eq!(
            DataProviderEnvironment::from_env(),
            DataProviderEnvironment::Development
        );

        std::env::remove_var("FOXHUNT_ENV");
        assert_eq!(
            DataProviderEnvironment::from_env(),
            DataProviderEnvironment::Development
        );
    }

    #[test]
    fn test_databento_defaults() {
        let config = DatabentoEndpoints::from_env(DataProviderEnvironment::Production);
        assert_eq!(
            config.websocket_url,
            "wss://gateway.databento.com/v0/subscribe"
        );
        assert_eq!(config.historical_base_url, "https://hist.databento.com");
    }

    #[test]
    fn test_benzinga_defaults() {
        let config = BenzingaEndpoints::from_env(DataProviderEnvironment::Production);
        assert_eq!(config.websocket_url, "wss://api.benzinga.com/api/v1/stream");
        assert_eq!(config.api_base_url, "https://api.benzinga.com/api/v2");
    }

    #[test]
    fn test_alpaca_defaults() {
        let dev_config = AlpacaEndpoints::from_env(DataProviderEnvironment::Development);
        assert_eq!(
            dev_config.trading_base_url,
            "https://paper-api.alpaca.markets"
        );

        let prod_config = AlpacaEndpoints::from_env(DataProviderEnvironment::Production);
        assert_eq!(prod_config.trading_base_url, "https://api.alpaca.markets");
    }

    #[test]
    fn test_ib_gateway_defaults() {
        let dev_config = IBGatewayConfig::from_env(DataProviderEnvironment::Development);
        assert_eq!(dev_config.host, "127.0.0.1");
        assert_eq!(dev_config.port, 7497);

        let prod_config = IBGatewayConfig::from_env(DataProviderEnvironment::Production);
        assert_eq!(prod_config.port, 7496);
    }

    #[test]
    fn test_environment_variable_override() {
        std::env::set_var("DATABENTO_WS_URL", "wss://custom.databento.com");
        let config = DatabentoEndpoints::from_env(DataProviderEnvironment::Production);
        assert_eq!(config.websocket_url, "wss://custom.databento.com");
        std::env::remove_var("DATABENTO_WS_URL");
    }

    #[test]
    fn test_master_config() {
        let config = DataProviderConfig::for_environment(DataProviderEnvironment::Production);
        assert_eq!(config.environment, DataProviderEnvironment::Production);
        assert!(!config.databento.websocket_url.is_empty());
        assert!(!config.benzinga.websocket_url.is_empty());
        assert!(!config.alpaca.trading_base_url.is_empty());
        assert!(!config.ib_gateway.host.is_empty());
    }
}
