//! Unified Error Hierarchy for Foxhunt HFT Trading System
//!
//! This module provides a comprehensive, unified error taxonomy that replaces
//! fragmented error types across all services. It implements enterprise-grade
//! error handling with proper error chains, severity classification, and
//! recovery strategies.

#![deny(clippy::unwrap_used, clippy::expect_used)]
#![warn(missing_docs)]

use chrono::{DateTime, Utc};
use common::error::ErrorCategory;
use serde::{Deserialize, Serialize};
use std::fmt;
use thiserror::Error;

// Re-export common error types for convenience
// TODO: Import these from common crate once they exist there
// pub use common::ConversionError;
// Note: ProtocolError and SymbolError are defined locally in this module

/// Conversion error types used by trading engine
#[derive(Error, Debug, Clone, PartialEq, Serialize, Deserialize)]
/// ConversionError
///
/// Auto-generated documentation placeholder - enhance with specifics
pub enum ConversionError {
    /// Invalid format error
    #[error("Invalid format: {0}")]
    // InvalidFormat variant
    InvalidFormat(String),
    /// Missing field error
    #[error("Missing field: {0}")]
    // MissingField variant
    MissingField(String),
    /// Type conversion error
    #[error("Type conversion failed: {0}")]
    // TypeConversion variant
    TypeConversion(String),
    /// Invalid number error
    #[error("Invalid number: {0}")]
    // InvalidNumber variant
    InvalidNumber(String),
}

impl ConversionError {
    /// Create an invalid format error
    pub fn invalid_format<S: Into<String>>(msg: S) -> Self {
        Self::InvalidFormat(msg.into())
    }

    /// Create a missing field error
    pub fn missing_field<S: Into<String>>(field: S) -> Self {
        Self::MissingField(field.into())
    }

    /// Create a type conversion error
    pub fn type_conversion<S: Into<String>>(msg: S) -> Self {
        Self::TypeConversion(msg.into())
    }

    /// Create an invalid number error
    pub fn invalid_number<S: Into<String>>(msg: S) -> Self {
        Self::InvalidNumber(msg.into())
    }
}

/// Protocol error types used by trading engine
///
/// Represents errors that occur during protocol communication
#[derive(Error, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ProtocolError {
    /// Protocol message error
    #[error("Protocol error: {message}")]
    MessageError {
        /// Error message describing the protocol issue
        message: String,
    },
}

impl ProtocolError {
    /// Create a new protocol error
    pub fn new<S: Into<String>>(message: S) -> Self {
        Self::MessageError {
            message: message.into(),
        }
    }
}

/// Symbol error types used by trading engine
#[derive(Error, Debug, Clone, PartialEq, Serialize, Deserialize)]
/// SymbolError
///
/// Auto-generated documentation placeholder - enhance with specifics
pub enum SymbolError {
    /// Invalid symbol format
    #[error("Invalid symbol format: {0}")]
    // InvalidFormat variant
    InvalidFormat(String),
    /// Symbol not found
    #[error("Symbol not found: {0}")]
    // NotFound variant
    NotFound(String),
}

impl SymbolError {
    /// Create an invalid format error
    pub fn invalid_format<S: Into<String>>(symbol: S) -> Self {
        Self::InvalidFormat(symbol.into())
    }

    /// Create a not found error
    pub fn not_found<S: Into<String>>(symbol: S) -> Self {
        Self::NotFound(symbol.into())
    }
}

/// Unified Error Hierarchy - Single Source of Truth for All Foxhunt Errors
///
/// This enum consolidates all error types across the entire trading platform,
/// providing consistent error handling, severity classification, and recovery strategies.
#[derive(Error, Debug, Clone, PartialEq, Serialize, Deserialize)]
/// FoxhuntError
///
/// Auto-generated documentation placeholder - enhance with specifics
pub enum FoxhuntError {
    // ========================================================================
    // P0 CRITICAL: Financial Safety Errors
    // ========================================================================
    /// Critical financial safety error - immediate emergency stop required
    #[error("CRITICAL FINANCIAL SAFETY: {message}")]
    FinancialSafety {
        /// Error description
        message: String,
        /// Financial context (price, quantity, calculation)
        context: Option<String>,
        /// Associated asset or symbol
        asset: Option<String>,
    },

    /// Invalid price value detected
    #[error("Invalid price {value}: {reason}")]
    InvalidPrice {
        /// The invalid price value
        value: String,
        /// Reason for invalidity
        reason: String,
        /// Associated symbol
        symbol: Option<String>,
    },

    /// Invalid quantity value detected
    #[error("Invalid quantity {value}: {reason}")]
    InvalidQuantity {
        /// The invalid quantity value
        value: String,
        /// Reason for invalidity
        reason: String,
        /// Associated symbol
        symbol: Option<String>,
    },

    /// Division by zero in financial calculation
    #[error("Division by zero in financial operation: {operation}")]
    DivisionByZero {
        /// The operation that attempted division by zero
        operation: String,
        /// Calculation context
        context: Option<String>,
    },

    /// Arithmetic overflow/underflow in financial calculations
    #[error("Arithmetic overflow in {operation}: {details}")]
    ArithmeticOverflow {
        /// The operation that overflowed
        operation: String,
        /// Overflow details
        details: String,
    },

    // ========================================================================
    // P1 HIGH: Trading Operations Errors
    // ========================================================================
    /// Order execution failure
    #[error("Order execution failed: {reason}")]
    OrderExecution {
        /// Execution failure reason
        reason: String,
        /// Order identifier
        order_id: Option<String>,
        /// Venue where execution failed
        venue: Option<String>,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    /// Invalid order state transition
    #[error("Invalid order state transition: {from} -> {to}")]
    InvalidOrderState {
        /// Current state
        from: String,
        /// Attempted target state
        to: String,
        /// Order identifier
        order_id: String,
        /// Transition context
        context: Option<String>,
    },

    /// Risk management failure
    #[error("Risk management failure: {reason}")]
    RiskManagement {
        /// Risk failure reason
        reason: String,
        /// Type of risk check that failed
        risk_type: String,
        /// Risk threshold that was breached
        threshold: Option<f64>,
        /// Associated position or order
        position_id: Option<String>,
    },

    /// Circuit breaker activation
    #[error("Circuit breaker {state}: {reason}")]
    CircuitBreaker {
        /// Circuit breaker state (Open, `HalfOpen`, Closed)
        state: String,
        /// Activation reason
        reason: String,
        /// Service or component
        component: String,
        /// Threshold that triggered the breaker
        threshold: Option<f64>,
    },

    /// Circuit breaker is open - operations rejected
    #[error("Circuit breaker open for {service}: {message}")]
    CircuitBreakerOpen {
        /// Service name
        service: String,
        /// Detailed message
        message: String,
        /// Additional context
        context: Option<String>,
    },

    /// Retry attempts exhausted
    #[error("Retry exhausted for {service} after {attempts} attempts in {elapsed:?}")]
    RetryExhausted {
        /// Service name
        service: String,
        /// Number of attempts made
        attempts: u32,
        /// Last error description
        last_error_description: String,
        /// Total time elapsed
        elapsed: std::time::Duration,
    },

    /// Kill switch activation
    #[error("Kill switch activated: {reason}")]
    KillSwitch {
        /// Kill switch activation reason
        reason: String,
        /// Component that triggered the kill switch
        component: String,
        /// Emergency context
        context: Option<String>,
    },

    /// Venue routing error
    #[error("Venue routing failed: {reason}")]
    VenueRouting {
        /// Routing failure reason
        reason: String,
        /// Target venue
        venue: Option<String>,
        /// Order details
        order_info: Option<String>,
    },

    // ========================================================================
    // P2 HIGH: System Infrastructure Errors
    // ========================================================================
    /// Database operation failure
    #[error("Database error: {operation} failed - {reason}")]
    Database {
        /// Database operation (insert, update, delete, select)
        operation: String,
        /// Failure reason
        reason: String,
        /// Database component (persistence, cache, etc.)
        component: String,
        /// SQL query or operation context
        query_context: Option<String>,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    /// Network connectivity failure
    #[error("Network error: {reason}")]
    Network {
        /// Network failure reason
        reason: String,
        /// Service or endpoint
        endpoint: Option<String>,
        /// Network operation (connect, send, receive)
        operation: Option<String>,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    /// System configuration error
    #[error("Configuration error: {reason}")]
    Configuration {
        /// Configuration error reason
        reason: String,
        /// Configuration key that failed
        config_key: Option<String>,
        /// Expected value or format
        expected: Option<String>,
        /// Actual value received
        actual: Option<String>,
    },

    /// System initialization failure
    #[error("System initialization failed: {component}")]
    Initialization {
        /// Component that failed to initialize
        component: String,
        /// Initialization stage
        stage: Option<String>,
        /// Failure reason
        reason: String,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    // ========================================================================
    // P2 HIGH: External Service Errors
    // ========================================================================
    /// Market data feed failure
    #[error("Market data error: {reason}")]
    MarketData {
        /// Market data failure reason
        reason: String,
        /// Data provider (Polygon, `ICMarkets`, IEX)
        provider: Option<String>,
        /// Affected symbol
        symbol: Option<String>,
        /// Data type (quotes, trades, orderbook)
        data_type: Option<String>,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    /// Broker connectivity failure
    #[error("Broker connection failed: {reason}")]
    BrokerConnection {
        /// Connection failure reason
        reason: String,
        /// Broker name (`InteractiveBrokers`, `ICMarkets`)
        broker: String,
        /// Connection protocol (FIX, REST, WebSocket)
        protocol: Option<String>,
        /// Connection endpoint
        endpoint: Option<String>,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    /// External service timeout
    #[error("Service timeout: {service} after {timeout_ms}ms")]
    ServiceTimeout {
        /// Service that timed out
        service: String,
        /// Timeout duration in milliseconds
        timeout_ms: u64,
        /// Operation that timed out
        operation: Option<String>,
    },

    /// External service rate limiting
    #[error("Rate limit exceeded: {service} - {limit} requests per {window}")]
    RateLimit {
        /// Service that imposed rate limit
        service: String,
        /// Rate limit threshold
        limit: u64,
        /// Time window
        window: String,
        /// Time until reset
        reset_time: Option<String>,
    },

    // ========================================================================
    // P2 MEDIUM: Business Logic Errors
    // ========================================================================
    /// Business rule violation
    #[error("Business logic error: {reason}")]
    BusinessLogic {
        /// Business rule violation reason
        reason: String,
        /// Business rule identifier
        rule_id: Option<String>,
        /// Context of the violation
        context: Option<String>,
    },

    /// Data validation failure
    #[error("Validation error: {field} - {reason}")]
    Validation {
        /// Field that failed validation
        field: String,
        /// Validation failure reason
        reason: String,
        /// Expected value or format
        expected: Option<String>,
        /// Actual value received
        actual: Option<String>,
    },

    /// Data parsing failure
    #[error("Parsing error: {reason}")]
    Parsing {
        /// Parsing failure reason
        reason: String,
        /// Data format being parsed
        format: Option<String>,
        /// Parsing context
        context: Option<String>,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    /// Protocol conversion failure
    #[error("Protocol conversion failed: {from} -> {to} - {reason}")]
    ProtocolConversion {
        /// Source protocol
        from: String,
        /// Target protocol
        to: String,
        /// Conversion failure reason
        reason: String,
        /// Data context
        data_context: Option<String>,
    },

    // ========================================================================
    // P2 MEDIUM: ML/AI Model Errors
    // ========================================================================
    /// ML model inference failure
    #[error("ML inference failed: {reason}")]
    MlInference {
        /// Inference failure reason
        reason: String,
        /// Model name
        model: String,
        /// Model version
        version: Option<String>,
        /// Input data context
        input_context: Option<String>,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    /// ML model training failure
    #[error("ML training failed: {reason}")]
    MlTraining {
        /// Training failure reason
        reason: String,
        /// Model name
        model: String,
        /// Training epoch or step
        epoch: Option<u64>,
        /// Training data context
        data_context: Option<String>,
    },

    /// GPU computation failure
    #[error("GPU computation failed: {reason}")]
    GpuComputation {
        /// GPU computation failure reason
        reason: String,
        /// GPU operation type
        operation: String,
        /// GPU device index
        device_id: Option<u32>,
        /// CUDA/OpenCL context
        context: Option<String>,
    },

    // ========================================================================
    // P3 MEDIUM: Security and Authentication Errors
    // ========================================================================
    /// Authentication failure
    #[error("Authentication failed: {reason}")]
    Authentication {
        /// Authentication failure reason
        reason: String,
        /// Authentication method
        method: Option<String>,
        /// User identifier
        user_id: Option<String>,
    },

    /// Authorization failure
    #[error("Authorization failed: {reason}")]
    Authorization {
        /// Authorization failure reason
        reason: String,
        /// Required permission
        permission: Option<String>,
        /// User identifier
        user_id: Option<String>,
        /// Resource being accessed
        resource: Option<String>,
    },

    /// Security violation
    #[error("Security violation: {reason}")]
    Security {
        /// Security violation reason
        reason: String,
        /// Security rule violated
        rule: Option<String>,
        /// Source of the violation
        source_info: Option<String>,
    },

    // ========================================================================
    // P3 LOW: Resource and State Errors
    // ========================================================================
    /// Resource not found
    #[error("Resource not found: {resource_type} '{resource_id}'")]
    NotFound {
        /// Type of resource
        resource_type: String,
        /// Resource identifier
        resource_id: String,
        /// Search context
        context: Option<String>,
    },

    /// Resource conflict (already exists)
    #[error("Resource conflict: {resource_type} '{resource_id}' already exists")]
    Conflict {
        /// Type of resource
        resource_type: String,
        /// Resource identifier
        resource_id: String,
        /// Conflict context
        context: Option<String>,
    },

    /// Invalid system state
    #[error("Invalid system state: {reason}")]
    InvalidState {
        /// State invalidity reason
        reason: String,
        /// Current state description
        current_state: Option<String>,
        /// Expected state description
        expected_state: Option<String>,
    },

    /// Internal system error
    #[error("Internal error: {reason}")]
    Internal {
        /// Internal error reason
        reason: String,
        /// Component where error occurred
        component: Option<String>,
        /// Error context
        context: Option<String>,
        /// Error source description (for serialization)
        source_description: Option<String>,
    },

    // ========================================================================
    // P3 LOW: Development and Testing Errors
    // ========================================================================
    /// Feature not implemented
    #[error("Feature not implemented: {feature}")]
    NotImplemented {
        /// Feature description
        feature: String,
        /// Implementation timeline
        timeline: Option<String>,
    },

    /// Test assertion failure
    #[error("Test assertion failed: {assertion}")]
    TestAssertion {
        /// Failed assertion description
        assertion: String,
        /// Test context
        test_context: Option<String>,
        /// Expected vs actual values
        details: Option<String>,
    },
}

/// Error Severity Classification
///
/// Provides consistent severity levels across all error types for
/// monitoring, alerting, and recovery strategy selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
/// ErrorSeverity
///
/// Auto-generated documentation placeholder - enhance with specifics
pub enum ErrorSeverity {
    /// Low severity - informational, system continues normally
    Low = 1,
    /// Medium severity - warning, degraded functionality possible
    Medium = 2,
    /// High severity - error requiring immediate attention
    High = 3,
    /// Critical severity - system-threatening, emergency procedures required
    Critical = 4,
}

impl fmt::Display for ErrorSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Low => write!(f, "LOW"),
            Self::Medium => write!(f, "MEDIUM"),
            Self::High => write!(f, "HIGH"),
            Self::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// Recovery Strategy Classification
///
/// Defines automated recovery actions for different error types,
/// enabling resilient system behavior under failure conditions.
#[derive(Debug, Clone, Serialize, Deserialize)]
/// RecoveryStrategy
///
/// Auto-generated documentation placeholder - enhance with specifics
pub enum RecoveryStrategy {
    /// Immediate emergency stop - halt all trading operations
    EmergencyStop,
    /// Retry with exponential backoff
    Retry {
        /// Maximum retry attempts
        max_attempts: u32,
        /// Initial backoff delay in milliseconds
        initial_delay_ms: u64,
        /// Backoff multiplier
        multiplier: f64,
        /// Maximum backoff delay in milliseconds
        max_delay_ms: u64,
    },
    /// Failover to alternative service/component
    Failover {
        /// Alternative service identifier
        fallback_service: String,
        /// Failover timeout in milliseconds
        timeout_ms: u64,
    },
    /// Circuit breaker activation
    CircuitBreaker {
        /// Failure threshold before opening
        failure_threshold: u32,
        /// Half-open retry delay in milliseconds
        retry_delay_ms: u64,
    },
    /// Graceful degradation - continue with reduced functionality
    GracefulDegradation {
        /// Degraded mode description
        degraded_mode: String,
        /// Features to disable
        disabled_features: Vec<String>,
    },
    /// Log error and continue normal operation
    LogAndContinue,
    /// Use default/safe values and continue
    UseDefaults {
        /// Default values description
        defaults: String,
    },
    /// Manual intervention required
    ManualIntervention {
        /// Escalation procedure
        escalation: String,
        /// Contact information
        contact: Option<String>,
    },
}

impl FoxhuntError {
    /// Get the severity level of this error
    #[must_use]
    pub const fn severity(&self) -> ErrorSeverity {
        match self {
            // Critical: Financial safety violations
            Self::FinancialSafety { .. }
            | Self::InvalidPrice { .. }
            | Self::InvalidQuantity { .. }
            | Self::DivisionByZero { .. }
            | Self::ArithmeticOverflow { .. }
            | Self::KillSwitch { .. } => ErrorSeverity::Critical,

            // High: Trading operations and system failures
            Self::OrderExecution { .. }
            | Self::InvalidOrderState { .. }
            | Self::RiskManagement { .. }
            | Self::CircuitBreaker { .. }
            | Self::CircuitBreakerOpen { .. }
            | Self::Database { .. }
            | Self::Initialization { .. }
            | Self::BrokerConnection { .. }
            | Self::Authentication { .. }
            | Self::Authorization { .. }
            | Self::Security { .. }
            | Self::Internal { .. } => ErrorSeverity::High,

            // Medium: External services and business logic
            Self::VenueRouting { .. }
            | Self::Network { .. }
            | Self::Configuration { .. }
            | Self::MarketData { .. }
            | Self::ServiceTimeout { .. }
            | Self::RateLimit { .. }
            | Self::RetryExhausted { .. }
            | Self::BusinessLogic { .. }
            | Self::Parsing { .. }
            | Self::ProtocolConversion { .. }
            | Self::MlInference { .. }
            | Self::MlTraining { .. }
            | Self::GpuComputation { .. }
            | Self::NotFound { .. }
            | Self::Conflict { .. }
            | Self::InvalidState { .. } => ErrorSeverity::Medium,

            // Low: Validation and development
            Self::Validation { .. } | Self::NotImplemented { .. } | Self::TestAssertion { .. } => {
                ErrorSeverity::Low
            },
        }
    }

    /// Get the recommended recovery strategy for this error
    #[must_use]
    pub fn recovery_strategy(&self) -> RecoveryStrategy {
        match self {
            // Emergency stop for critical financial errors
            Self::FinancialSafety { .. }
            | Self::InvalidPrice { .. }
            | Self::InvalidQuantity { .. }
            | Self::DivisionByZero { .. }
            | Self::ArithmeticOverflow { .. }
            | Self::KillSwitch { .. } => RecoveryStrategy::EmergencyStop,

            // Retry for transient network and service errors
            Self::Network { .. }
            | Self::ServiceTimeout { .. }
            | Self::BrokerConnection { .. }
            | Self::MarketData { .. } => RecoveryStrategy::Retry {
                max_attempts: 3,
                initial_delay_ms: 1000,
                multiplier: 2.0,
                max_delay_ms: 30000,
            },

            // Circuit breaker for order execution
            Self::OrderExecution { .. } => RecoveryStrategy::CircuitBreaker {
                failure_threshold: 5,
                retry_delay_ms: 10000,
            },

            // Circuit breaker open - wait for recovery
            Self::CircuitBreakerOpen { .. } => RecoveryStrategy::CircuitBreaker {
                failure_threshold: 3,
                retry_delay_ms: 5000,
            },

            // Retry exhausted - escalate or use degraded mode
            Self::RetryExhausted { .. } => RecoveryStrategy::GracefulDegradation {
                degraded_mode: "fallback_service".to_owned(),
                disabled_features: vec!["advanced_features".to_owned()],
            },

            // Failover for venue routing
            Self::VenueRouting { .. } => RecoveryStrategy::Failover {
                fallback_service: "backup_venue".to_owned(),
                timeout_ms: 5000,
            },

            // Graceful degradation for ML model failures
            Self::MlInference { .. } | Self::MlTraining { .. } | Self::GpuComputation { .. } => {
                RecoveryStrategy::GracefulDegradation {
                    degraded_mode: "fallback_model".to_owned(),
                    disabled_features: vec!["advanced_predictions".to_owned()],
                }
            },

            // Use defaults for configuration errors
            Self::Configuration { .. } => RecoveryStrategy::UseDefaults {
                defaults: "safe_default_values".to_owned(),
            },

            // Manual intervention for critical system errors
            Self::Database { .. }
            | Self::Initialization { .. }
            | Self::RiskManagement { .. }
            | Self::Security { .. } => RecoveryStrategy::ManualIntervention {
                escalation: "alert_operations_team".to_owned(),
                contact: Some("ops-team@foxhunt.trading".to_owned()),
            },

            // Log and continue for most other errors
            Self::InvalidOrderState { .. }
            | Self::CircuitBreaker { .. }
            | Self::RateLimit { .. }
            | Self::BusinessLogic { .. }
            | Self::Validation { .. }
            | Self::Parsing { .. }
            | Self::ProtocolConversion { .. }
            | Self::Authentication { .. }
            | Self::Authorization { .. }
            | Self::NotFound { .. }
            | Self::Conflict { .. }
            | Self::InvalidState { .. }
            | Self::Internal { .. }
            | Self::NotImplemented { .. }
            | Self::TestAssertion { .. } => RecoveryStrategy::LogAndContinue,
        }
    }

    /// Check if this error is retryable
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        matches!(
            self.recovery_strategy(),
            RecoveryStrategy::Retry { .. } | RecoveryStrategy::CircuitBreaker { .. }
        )
    }

    /// Get the error category for monitoring and grouping
    #[must_use]
    pub const fn category(&self) -> ErrorCategory {
        match self {
            Self::FinancialSafety { .. }
            | Self::InvalidPrice { .. }
            | Self::InvalidQuantity { .. }
            | Self::DivisionByZero { .. }
            | Self::ArithmeticOverflow { .. } => ErrorCategory::FinancialSafety,

            Self::OrderExecution { .. }
            | Self::InvalidOrderState { .. }
            | Self::VenueRouting { .. } => ErrorCategory::Trading,

            Self::RiskManagement { .. }
            | Self::CircuitBreaker { .. }
            | Self::CircuitBreakerOpen { .. }
            | Self::RetryExhausted { .. }
            | Self::KillSwitch { .. } => ErrorCategory::RiskManagement,

            Self::Database { .. } => ErrorCategory::Database,

            Self::Network { .. } | Self::ServiceTimeout { .. } | Self::RateLimit { .. } => {
                ErrorCategory::Network
            },

            Self::MarketData { .. } => ErrorCategory::MarketData,

            Self::BrokerConnection { .. } => ErrorCategory::Broker,

            Self::MlInference { .. } | Self::MlTraining { .. } | Self::GpuComputation { .. } => {
                ErrorCategory::MachineLearning
            },

            Self::Authentication { .. } | Self::Authorization { .. } | Self::Security { .. } => {
                ErrorCategory::Security
            },

            Self::Configuration { .. }
            | Self::Initialization { .. }
            | Self::InvalidState { .. }
            | Self::Internal { .. } => ErrorCategory::System,

            Self::BusinessLogic { .. } => ErrorCategory::BusinessLogic,

            Self::Validation { .. } | Self::Parsing { .. } | Self::ProtocolConversion { .. } => {
                ErrorCategory::Validation
            },

            Self::NotFound { .. } | Self::Conflict { .. } => ErrorCategory::Resource,

            Self::NotImplemented { .. } | Self::TestAssertion { .. } => ErrorCategory::Development,
        }
    }

    /// Create a comprehensive error context for logging and monitoring
    #[must_use]
    pub fn error_context(&self) -> ErrorContext {
        ErrorContext {
            severity: self.severity(),
            category: self.category(),
            recovery_strategy: self.recovery_strategy(),
            is_retryable: self.is_retryable(),
            timestamp: Utc::now(),
            error_id: uuid::Uuid::new_v4().to_string(),
        }
    }
}

// ErrorCategory is now imported from common::error

// ErrorCategory Display impl is now in common::error

/// Comprehensive Error Context
///
/// Provides metadata for error monitoring, alerting, and analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
/// ErrorContext
///
/// Auto-generated documentation placeholder - enhance with specifics
pub struct ErrorContext {
    /// Error severity level
    pub severity: ErrorSeverity,
    /// Error functional category
    pub category: ErrorCategory,
    /// Recommended recovery strategy
    pub recovery_strategy: RecoveryStrategy,
    /// Whether the error is retryable
    pub is_retryable: bool,
    /// Error occurrence timestamp
    pub timestamp: DateTime<Utc>,
    /// Unique error identifier
    pub error_id: String,
}

/// Unified `Result` type for all Foxhunt operations
pub type FoxhuntResult<T> = Result<T, FoxhuntError>;

// ============================================================================
// CONVERSION IMPLEMENTATIONS
// ============================================================================

// Existing error type conversions for backward compatibility
impl From<ConversionError> for FoxhuntError {
    fn from(err: ConversionError) -> Self {
        match err {
            ConversionError::InvalidFormat(msg) => Self::Parsing {
                reason: format!("Invalid format: {msg}"),
                format: Some("conversion".to_owned()),
                context: None,
                source_description: None,
            },
            ConversionError::MissingField(field) => Self::Validation {
                field,
                reason: "Missing required field".to_owned(),
                expected: None,
                actual: None,
            },
            ConversionError::TypeConversion(msg) => Self::ProtocolConversion {
                from: "unknown".to_owned(),
                to: "unknown".to_owned(),
                reason: msg,
                data_context: None,
            },
            ConversionError::InvalidNumber(msg) => Self::Validation {
                field: "number".to_owned(),
                reason: format!("Invalid number: {msg}"),
                expected: Some("valid_number".to_owned()),
                actual: Some(msg),
            },
        }
    }
}

impl From<SymbolError> for FoxhuntError {
    fn from(err: SymbolError) -> Self {
        match err {
            SymbolError::InvalidFormat(symbol) => Self::Validation {
                field: "symbol".to_owned(),
                reason: "Invalid symbol format".to_owned(),
                expected: Some("valid_symbol_format".to_owned()),
                actual: Some(symbol),
            },
            SymbolError::NotFound(symbol) => Self::NotFound {
                resource_type: "symbol".to_owned(),
                resource_id: symbol,
                context: None,
            },
        }
    }
}

impl From<ProtocolError> for FoxhuntError {
    fn from(err: ProtocolError) -> Self {
        let message = match err {
            ProtocolError::MessageError { message } => message,
        };
        Self::ProtocolConversion {
            from: "unknown".to_owned(),
            to: "unknown".to_owned(),
            reason: message,
            data_context: None,
        }
    }
}

// Standard library error conversions
impl From<std::io::Error> for FoxhuntError {
    fn from(err: std::io::Error) -> Self {
        Self::Internal {
            reason: format!("IO error: {err}"),
            component: Some("filesystem".to_owned()),
            context: None,
            source_description: Some(format!("std::io::Error: {err}")),
        }
    }
}

impl From<std::num::ParseFloatError> for FoxhuntError {
    fn from(err: std::num::ParseFloatError) -> Self {
        Self::Parsing {
            reason: format!("Float parsing error: {err}"),
            format: Some("float".to_owned()),
            context: None,
            source_description: Some(format!("std::num::ParseFloatError: {err}")),
        }
    }
}

impl From<std::num::ParseIntError> for FoxhuntError {
    fn from(err: std::num::ParseIntError) -> Self {
        Self::Parsing {
            reason: format!("Integer parsing error: {err}"),
            format: Some("integer".to_owned()),
            context: None,
            source_description: Some(format!("std::num::ParseIntError: {err}")),
        }
    }
}

impl From<serde_json::Error> for FoxhuntError {
    fn from(err: serde_json::Error) -> Self {
        Self::Parsing {
            reason: format!("JSON parsing error: {err}"),
            format: Some("json".to_owned()),
            context: None,
            source_description: Some(format!("serde_json::Error: {err}")),
        }
    }
}

// Note: HTTP-specific error conversions will be implemented in service layers
// that actually use reqwest, not in the core types crate

// ============================================================================
// ERROR HELPER MACROS AND FUNCTIONS
// ============================================================================

/// Create a financial safety error with context
pub fn financial_safety_error<M, C, A>(
    message: M,
    context: Option<C>,
    asset: Option<A>,
) -> FoxhuntError
where
    M: Into<String>,
    C: Into<String>,
    A: Into<String>,
{
    FoxhuntError::FinancialSafety {
        message: message.into(),
        context: context.map(Into::into),
        asset: asset.map(Into::into),
    }
}

/// Create an order execution error with full context
pub fn order_execution_error<R, O, V, S>(
    reason: R,
    order_id: Option<O>,
    venue: Option<V>,
    source_description: Option<S>,
) -> FoxhuntError
where
    R: Into<String>,
    O: Into<String>,
    V: Into<String>,
    S: Into<String>,
{
    FoxhuntError::OrderExecution {
        reason: reason.into(),
        order_id: order_id.map(Into::into),
        venue: venue.map(Into::into),
        source_description: source_description.map(Into::into),
    }
}

/// Create a risk management error with context
pub fn risk_management_error<R, T, P>(
    reason: R,
    risk_type: T,
    threshold: Option<f64>,
    position_id: Option<P>,
) -> FoxhuntError
where
    R: Into<String>,
    T: Into<String>,
    P: Into<String>,
{
    FoxhuntError::RiskManagement {
        reason: reason.into(),
        risk_type: risk_type.into(),
        threshold,
        position_id: position_id.map(Into::into),
    }
}

/// Create a database error with full context
pub fn database_error<O, R, C, Q, S>(
    operation: O,
    reason: R,
    component: C,
    query_context: Option<Q>,
    source_description: Option<S>,
) -> FoxhuntError
where
    O: Into<String>,
    R: Into<String>,
    C: Into<String>,
    Q: Into<String>,
    S: Into<String>,
{
    FoxhuntError::Database {
        operation: operation.into(),
        reason: reason.into(),
        component: component.into(),
        query_context: query_context.map(Into::into),
        source_description: source_description.map(Into::into),
    }
}

/// Create a market data error with full context
pub fn market_data_error<R, P, S, D, E>(
    reason: R,
    provider: Option<P>,
    symbol: Option<S>,
    data_type: Option<D>,
    source_description: Option<E>,
) -> FoxhuntError
where
    R: Into<String>,
    P: Into<String>,
    S: Into<String>,
    D: Into<String>,
    E: Into<String>,
{
    FoxhuntError::MarketData {
        reason: reason.into(),
        provider: provider.map(Into::into),
        symbol: symbol.map(Into::into),
        data_type: data_type.map(Into::into),
        source_description: source_description.map(Into::into),
    }
}

/// Create a validation error with detailed context
pub fn validation_error<F, R, E, A>(
    field: F,
    reason: R,
    expected: Option<E>,
    actual: Option<A>,
) -> FoxhuntError
where
    F: Into<String>,
    R: Into<String>,
    E: Into<String>,
    A: Into<String>,
{
    FoxhuntError::Validation {
        field: field.into(),
        reason: reason.into(),
        expected: expected.map(Into::into),
        actual: actual.map(Into::into),
    }
}

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

    #[test]
    fn test_financial_safety_error_severity() {
        let error = FoxhuntError::FinancialSafety {
            message: "Invalid price calculation".to_string(),
            context: Some("order_processing".to_string()),
            asset: Some("AAPL".to_string()),
        };
        assert_eq!(error.severity(), ErrorSeverity::Critical);
        assert_eq!(error.category(), ErrorCategory::FinancialSafety);
        assert!(matches!(
            error.recovery_strategy(),
            RecoveryStrategy::EmergencyStop
        ));
    }

    #[test]
    fn test_order_execution_error_context() {
        let error = FoxhuntError::OrderExecution {
            reason: "Venue timeout".to_string(),
            order_id: Some("ORD123".to_string()),
            venue: Some("SMART".to_string()),
            source_description: None,
        };

        let context = error.error_context();
        assert_eq!(context.severity, ErrorSeverity::High);
        assert_eq!(context.category, ErrorCategory::Trading);
        assert!(context.is_retryable);
    }

    #[test]
    fn test_network_error_retry_strategy() {
        let error = FoxhuntError::Network {
            reason: "Connection refused".to_string(),
            endpoint: Some("localhost:8080".to_string()),
            operation: Some("connect".to_string()),
            source_description: None,
        };

        match error.recovery_strategy() {
            RecoveryStrategy::Retry { max_attempts, .. } => {
                assert_eq!(max_attempts, 3);
            },
            _ => panic!("Expected retry strategy for network error"),
        }
    }

    #[test]
    fn test_error_category_display() {
        assert_eq!(
            ErrorCategory::FinancialSafety.to_string(),
            "FINANCIAL_SAFETY"
        );
        assert_eq!(ErrorCategory::Trading.to_string(), "TRADING");
        assert_eq!(ErrorCategory::Network.to_string(), "NETWORK");
    }

    #[test]
    fn test_error_severity_ordering() {
        assert!(ErrorSeverity::Critical > ErrorSeverity::High);
        assert!(ErrorSeverity::High > ErrorSeverity::Medium);
        assert!(ErrorSeverity::Medium > ErrorSeverity::Low);
    }

    #[test]
    fn test_conversion_from_std_errors() {
        let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
        let foxhunt_error: FoxhuntError = io_error.into();

        match foxhunt_error {
            FoxhuntError::Internal {
                reason, component, ..
            } => {
                assert!(reason.contains("IO error"));
                assert_eq!(component, Some("filesystem".to_string()));
            },
            _ => panic!("Expected Internal error for IO error"),
        }
    }

    #[test]
    fn test_helper_functions() {
        let financial_error =
            financial_safety_error("Division by zero", Some("price_calculation"), Some("AAPL"));

        match financial_error {
            FoxhuntError::FinancialSafety {
                message,
                context,
                asset,
            } => {
                assert_eq!(message, "Division by zero");
                assert_eq!(context, Some("price_calculation".to_string()));
                assert_eq!(asset, Some("AAPL".to_string()));
            },
            _ => panic!("Expected FinancialSafety error"),
        }
    }

    #[test]
    fn test_error_serialization() {
        let error = FoxhuntError::Validation {
            field: "price".to_string(),
            reason: "Must be positive".to_string(),
            expected: Some(">0".to_string()),
            actual: Some("-10.5".to_string()),
        };

        let json = serde_json::to_string(&error).expect("Should serialize");
        let deserialized: FoxhuntError = serde_json::from_str(&json).expect("Should deserialize");

        match deserialized {
            FoxhuntError::Validation { field, reason, .. } => {
                assert_eq!(field, "price");
                assert_eq!(reason, "Must be positive");
            },
            _ => panic!("Expected Validation error after deserialization"),
        }
    }
}
