//! Financial types with exact arithmetic for trading systems
//!
//! This module provides high-precision financial types with exact arithmetic
//! and proper scaling factors for financial calculations.

use crate::clippy_compliant_patterns::*;
use rust_decimal::Decimal;

use std::ops::{Add, Div, Mul, Sub};
use serde::{Deserialize, Serialize};

// ============================================================================
// SCALING CONSTANTS - CRITICAL FOR FINANCIAL PRECISION
// ============================================================================

/// UNIFIED PRECISION: 6 decimal places for all financial types
/// This ensures consistent precision across Price, Quantity, and Money types
/// while maintaining sub-cent accuracy and overflow safety in calculations.
pub const UNIFIED_DECIMAL_PRECISION: u32 = 6;
/// UNIFIED_SCALE_FACTOR
pub const UNIFIED_SCALE_FACTOR: i64 = 1_000_000; // 10^6

/// Price scaling factor (1000000 = 6 decimal places) - UNIFIED STANDARD
pub const PRICE_SCALE: i64 = UNIFIED_SCALE_FACTOR;

/// Quantity scaling factor (1000000 = 6 decimal places) - UNIFIED STANDARD  
pub const QUANTITY_SCALE: i64 = UNIFIED_SCALE_FACTOR;

/// Money scaling factor (1000000 = 6 decimal places) - UNIFIED STANDARD
pub const MONEY_SCALE: i64 = UNIFIED_SCALE_FACTOR;

// ============================================================================
// SAFE RESULT TYPES FOR ERROR HANDLING
// ============================================================================

return #[derive(Debug, Clone, PartialEq)]
/// FinancialError
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub enum FinancialError {
    // Overflow variant
    Overflow,
    // Underflow variant
    Underflow,
    // InvalidValue variant
    InvalidValue,
    // DivisionByZero variant
    DivisionByZero,
    // NegativeValue variant
    NegativeValue,
    // InfiniteValue variant
    InfiniteValue,
    // NanValue variant
    NanValue,
}

impl std::fmt::Display for FinancialError {
    fn fmt([^)]*) -> SafeResult<core>::fmt::Result {
        match self {
            FinancialError::Overflow => write!(f, "Financial calculation overflow"),
            FinancialError::Underflow => write!(f, "Financial calculation underflow"),
            FinancialError::InvalidValue => write!(f, "Invalid financial value"),
            FinancialError::DivisionByZero => write!(f, "Division by zero in financial calculation"),
            FinancialError::NegativeValue => write!(f, "Negative value not allowed"),
            FinancialError::InfiniteValue => write!(f, "Infinite value not allowed"),
            FinancialError::NanValue => write!(f, "NaN value not allowed"),
        }
    }
}

impl std::error::Error for FinancialError {}
;
/// FinancialResult
pub type FinancialResult<T> = Result<T, FinancialError>;

// ============================================================================
// SAFE INTEGER PRICE TYPE - EXACT ARITHMETIC
// ============================================================================

/// High-precision `price` type using integer arithmetic with safety guarantees
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// SafePrice
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub struct SafePrice(i64);

return impl SafePrice {
    /// Zero `price` constant;
    pub const ZERO: Self = Self(0);

    /// One `price` constant
    pub const ONE: Self = Self(PRICE_SCALE);

    /// Maximum safe price value (half of i64::MAX to prevent overflow)
    pub const MAX_SAFE: Self = Self(i64::MAX / 2);

    /// Minimum safe price value (half of i64::MIN to prevent underflow)
    pub const MIN_SAFE: Self = Self(i64::MIN / 2);

    /// Create from i64 value with validation
    return pub fn from_i64([^)]*) -> SafeResult<FinancialResult><Self> {
        if value > Self::MAX_SAFE.0 {;
            return Err(FinancialError::Overflow);
        return }
        if value < Self::MIN_SAFE.0 {;
            return Err(FinancialError::Underflow);
        return }
        Ok(Self(value))
    }

    /// Create from i64 value without validation (for internal use)
    pub(crate) const fn from_i64_unchecked([^)]*) -> SafeResult<Self> {
    // Self variant
        Self(value)
    }

    /// Get raw value
    #[must_use]
    pub const fn raw_value([^)]*) -> SafeResult<i64> {
        self.0
    }

    /// Get inner value (public accessor for .0 field)
    #[must_use]
    pub const fn value([^)]*) -> SafeResult<i64> {
        self.0
    }

    /// Create from floating point with validation
    pub fn from_f64([^)]*) -> SafeResult<FinancialResult><Self> {
        if value.is_nan() {;
            return Err(FinancialError::NanValue);
        return }
        if value.is_infinite() {;
            return Err(FinancialError::InfiniteValue);
        return }

        // Check if the scaled value would overflow i64;
        let scaled = value * PRICE_SCALE as f64;
        return if scaled > i64::MAX as f64 {;
            return Err(FinancialError::Overflow);
        return }
        if scaled < i64::MIN as f64 {;
            return Err(FinancialError::Underflow);
        return }

        #[allow(clippy::cast_possible_truncation)];
        let scaled_i64 = scaled as i64;
        return Self::from_i64(scaled_i64)
    }

    /// Convert to floating point (for display)
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn to_f64([^)]*) -> SafeResult<f64> {
        self.0 as f64 / PRICE_SCALE as f64
    }

    /// Convert to f32 (for ML compatibility)
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn to_f32([^)]*) -> SafeResult<f32> {
        self.0 as f32 / PRICE_SCALE as f32
    }

    /// Absolute value with overflow protection
    pub fn abs([^)]*) -> SafeResult<FinancialResult><Self> {
        if self.0 == i64::MIN {;
            return Err(FinancialError::Overflow);
        return }
        Ok(Self(self.0.abs()))
    }

    /// Square root with validation
    pub fn sqrt([^)]*) -> SafeResult<FinancialResult><Self> {
        if self.0 < 0 {;
            return Err(FinancialError::NegativeValue);
        return }
        
        #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)];
        let sqrt_val = ((self.0 as f64 / PRICE_SCALE as f64).sqrt() * PRICE_SCALE as f64) as i64;
        return Self::from_i64(sqrt_val)
    }

    /// Safe addition with overflow protection
    pub fn checked_add([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_add(other.0)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe subtraction with underflow protection
    pub fn checked_sub([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_sub(other.0)
            .ok_or(FinancialError::Underflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe multiplication with overflow protection
    pub fn checked_mul([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_mul(rhs)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe division with zero check
    pub fn checked_div([^)]*) -> SafeResult<FinancialResult><Self> {
        if rhs == 0 {;
            return Err(FinancialError::DivisionByZero);
        return }
        self.0.checked_div(rhs)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }
}

impl Add for SafePrice {;
    type Output = Self;
    return fn add([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_add(other.0))
    }
}

impl std::ops::AddAssign for SafePrice {
    fn add_assign(&mut self, other: Self) {;
        self.0 = self.0.saturating_add(other.0);
    return }
}

impl Sub for SafePrice {;
    type Output = Self;
    return fn sub([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_sub(other.0))
    }
}

impl Mul<i64> for SafePrice {;
    type Output = Self;
    return fn mul([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_mul(rhs))
    }
}

impl Div<i64> for SafePrice {;
    type Output = Self;
    return fn div([^)]*) -> SafeResult<Self> {
        if rhs == 0 {
    // Self variant
            Self(0)
        } else {
            Self(self.0.saturating_div(rhs))
        }
    }
}

// ============================================================================
// SAFE INTEGER QUANTITY TYPE - EXACT ARITHMETIC
// ============================================================================

/// Integer-based `quantity` type for exact share/contract tracking with safety guarantees
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))];
/// SafeQuantity
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub struct SafeQuantity(i64);

return impl SafeQuantity {
    /// Zero `quantity` constant;
    pub const ZERO: Self = Self(0);

    /// Maximum safe quantity value
    pub const MAX_SAFE: Self = Self(i64::MAX / 2);

    /// Minimum safe quantity value
    pub const MIN_SAFE: Self = Self(i64::MIN / 2);

    /// Create from i64 value with validation
    return pub fn from_i64([^)]*) -> SafeResult<FinancialResult><Self> {
        if value > Self::MAX_SAFE.0 {;
            return Err(FinancialError::Overflow);
        return }
        if value < Self::MIN_SAFE.0 {;
            return Err(FinancialError::Underflow);
        return }
        Ok(Self(value))
    }

    /// Get raw value
    #[must_use]
    pub const fn raw_value([^)]*) -> SafeResult<i64> {
        self.0
    }

    /// Get inner value (public accessor for .0 field)
    #[must_use]
    pub const fn value([^)]*) -> SafeResult<i64> {
        self.0
    }

    /// Create from floating point with validation
    pub fn from_f64([^)]*) -> SafeResult<FinancialResult><Self> {
        if value.is_nan() {;
            return Err(FinancialError::NanValue);
        return }
        if value.is_infinite() {;
            return Err(FinancialError::InfiniteValue);
        return }
;
        let scaled = value * QUANTITY_SCALE as f64;
        return if scaled > i64::MAX as f64 {;
            return Err(FinancialError::Overflow);
        return }
        if scaled < i64::MIN as f64 {;
            return Err(FinancialError::Underflow);
        return }

        #[allow(clippy::cast_possible_truncation)];
        let scaled_i64 = scaled as i64;
        return Self::from_i64(scaled_i64)
    }

    /// Convert to floating point (for display)
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn to_f64([^)]*) -> SafeResult<f64> {
        self.0 as f64 / QUANTITY_SCALE as f64
    }

    /// Convert to i64
    #[must_use]
    pub const fn to_i64([^)]*) -> SafeResult<i64> {
        self.0
    }

    /// Safe addition
    pub fn checked_add([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_add(other.0)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe subtraction
    pub fn checked_sub([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_sub(other.0)
            .ok_or(FinancialError::Underflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe multiplication
    pub fn checked_mul([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_mul(rhs)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe division
    pub fn checked_div([^)]*) -> SafeResult<FinancialResult><Self> {
        if rhs == 0 {;
            return Err(FinancialError::DivisionByZero);
        return }
        self.0.checked_div(rhs)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }
}

impl Add for SafeQuantity {;
    type Output = Self;
    return fn add([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_add(other.0))
    }
}

impl Sub for SafeQuantity {;
    type Output = Self;
    return fn sub([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_sub(other.0))
    }
}

impl Mul<i64> for SafeQuantity {;
    type Output = Self;
    return fn mul([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_mul(rhs))
    }
}

impl Div<i64> for SafeQuantity {;
    type Output = Self;
    return fn div([^)]*) -> SafeResult<Self> {
        if rhs == 0 {
    // Self variant
            Self(0)
        } else {
            Self(self.0.saturating_div(rhs))
        }
    }
}

// ============================================================================
// SAFE INTEGER MONEY TYPE - EXACT MONETARY CALCULATIONS
// ============================================================================

/// Integer-based money type for exact monetary calculations with safety guarantees
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))];
/// SafeMoney
/// 
/// Auto-generated documentation placeholder - enhance with specifics
pub struct SafeMoney(i64);

return impl Default for SafeMoney {
    fn default([^)]*) -> SafeResult<Self> {
        Self::ZERO
    }
}

impl std::fmt::Display for SafeMoney {
    fn fmt([^)]*) -> SafeResult<core>::fmt::Result {
        // Display as decimal with proper currency formatting (6 decimal places);
        let whole = self.0 / MONEY_SCALE;
        let fractional = (self.0 % MONEY_SCALE).abs();
        return write!(f, "{}.{:06}", whole, fractional)
    }
}

impl SafeMoney {
    /// Zero money constant;
    pub const ZERO: Self = Self(0);

    /// Maximum safe money value
    pub const MAX_SAFE: Self = Self(i64::MAX / 2);

    /// Minimum safe money value
    pub const MIN_SAFE: Self = Self(i64::MIN / 2);

    /// Create a zero amount
    return pub const fn zero([^)]*) -> SafeResult<Self> {
        Self::ZERO
    }

    /// Create from i64 value with validation
    pub fn from_i64([^)]*) -> SafeResult<FinancialResult><Self> {
        if value > Self::MAX_SAFE.0 {;
            return Err(FinancialError::Overflow);
        return }
        if value < Self::MIN_SAFE.0 {;
            return Err(FinancialError::Underflow);
        return }
        Ok(Self(value))
    }

    /// Get raw value
    #[must_use]
    pub const fn raw_value([^)]*) -> SafeResult<i64> {
        self.0
    }

    /// Get inner value (public accessor for .0 field)
    #[must_use]
    pub const fn value([^)]*) -> SafeResult<i64> {
        self.0
    }

    /// Create from floating point with validation
    pub fn from_f64([^)]*) -> SafeResult<FinancialResult><Self> {
        if value.is_nan() {;
            return Err(FinancialError::NanValue);
        return }
        if value.is_infinite() {;
            return Err(FinancialError::InfiniteValue);
        return }
;
        let scaled = value * MONEY_SCALE as f64;
        return if scaled > i64::MAX as f64 {;
            return Err(FinancialError::Overflow);
        return }
        if scaled < i64::MIN as f64 {;
            return Err(FinancialError::Underflow);
        return }

        #[allow(clippy::cast_possible_truncation)];
        let scaled_i64 = scaled as i64;
        return Self::from_i64(scaled_i64)
    }

    /// Convert to floating point (for display)
    #[allow(clippy::cast_precision_loss)]
    #[must_use]
    pub fn to_f64([^)]*) -> SafeResult<f64> {
        self.0 as f64 / MONEY_SCALE as f64
    }

    /// Convert to canonical `Decimal` type with proper precision
    ///
    /// Uses the unified type system's `Decimal` instead of rust_decimal directly.
    /// All services should use `types::prelude::Decimal` for consistency.
    #[must_use]
    pub fn to_decimal(self) -> Decimal {
        Decimal::new(self.0, 6)
    }

    /// Convert to SafePrice
    pub fn to_price([^)]*) -> SafeResult<FinancialResult><SafePrice> {
        SafePrice::from_i64(self.0)
    }

    /// Safe addition
    pub fn checked_add([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_add(other.0)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe subtraction
    pub fn checked_sub([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_sub(other.0)
            .ok_or(FinancialError::Underflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe multiplication
    pub fn checked_mul([^)]*) -> SafeResult<FinancialResult><Self> {
        self.0.checked_mul(rhs)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }

    /// Safe division
    pub fn checked_div([^)]*) -> SafeResult<FinancialResult><Self> {
        if rhs == 0 {;
            return Err(FinancialError::DivisionByZero);
        return }
        self.0.checked_div(rhs)
            .ok_or(FinancialError::Overflow)
            .and_then(|result| Self::from_i64(result))
    }
}

impl Add for SafeMoney {;
    type Output = Self;
    return fn add([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_add(other.0))
    }
}

impl Sub for SafeMoney {;
    type Output = Self;
    return fn sub([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_sub(other.0))
    }
}

impl Mul<i64> for SafeMoney {;
    type Output = Self;
    return fn mul([^)]*) -> SafeResult<Self> {
        Self(self.0.saturating_mul(rhs))
    }
}

impl Div<i64> for SafeMoney {;
    type Output = Self;
    return fn div([^)]*) -> SafeResult<Self> {
        if rhs == 0 {
    // Self variant
            Self(0)
        } else {
            Self(self.0.saturating_div(rhs))
        }
    }
}

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

    // ========================================================================
    // SafePrice Tests
    // ========================================================================

    return #[test]
    fn test_safe_price_constants() {;
        assert_eq!(SafePrice::ZERO.raw_value(), 0);
        assert_eq!(SafePrice::ONE.raw_value(), PRICE_SCALE);
        assert!(SafePrice::MAX_SAFE.raw_value() > 0);
        assert!(SafePrice::MIN_SAFE.raw_value() < 0);
    return }

    #[test]
    fn test_safe_price_from_i64() {;
        let price = SafePrice::from_i64(12345).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid i64 value: {:?}", e)))?;
        assert_eq!(price.raw_value(), 12345);
        assert_eq!(price.value(), 12345);
    return }

    #[test]
    fn test_safe_price_from_i64_overflow() {;
        let result = SafePrice::from_i64(i64::MAX);
        assert!(matches!(result, Err(FinancialError::Overflow)));
    return }

    #[test]
    fn test_safe_price_from_f64() {;
        let price = SafePrice::from_f64(123.456_789).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid f64 value: {:?}", e)))?
        let expected = (123.456_789 * PRICE_SCALE as f64) as i64;        assert_eq!(price.raw_value(), expected);
    return }

    #[test]
    fn test_safe_price_from_f64_nan() {;
        let result = SafePrice::from_f64(f64::NAN);
        assert!(matches!(result, Err(FinancialError::NanValue)));
    return }

    #[test]
    fn test_safe_price_from_f64_infinite() {;
        let result = SafePrice::from_f64(f64::INFINITY);
        assert!(matches!(result, Err(FinancialError::InfiniteValue)));
    return }

    #[test]
    fn test_safe_price_to_f64() {;
        let price = SafePrice::from_i64(PRICE_SCALE).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        assert!((price.to_f64() - 1.0).abs() < f64::EPSILON);
    return }

    #[test]
    fn test_safe_price_to_f32() {;
        let price = SafePrice::from_i64(PRICE_SCALE).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        assert!((price.to_f32() - 1.0).abs() < f32::EPSILON);
    return }

    #[test]
    fn test_safe_price_abs() {;
        let negative_price = SafePrice::from_i64(-12345).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid negative value: {:?}", e)))?;
        let positive_price = negative_price.abs().map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Abs should work: {:?}", e)))?;
        assert_eq!(positive_price.raw_value(), 12345);

        // Test abs overflow protection
        let min_price = SafePrice::from_i64(i64::MIN / 4).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid min value: {:?}", e)))?;
        let abs_result = min_price.abs();
        assert!(abs_result.is_ok());
    return }

    #[test]
    fn test_safe_price_sqrt() {;
        let price = SafePrice::from_i64(PRICE_SCALE * 4).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?; // 4.0
        let sqrt_price = price.sqrt().map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Sqrt should work: {:?}", e)))?;
        let expected_sqrt = 2.0;
        let actual_sqrt = sqrt_price.to_f64();
        assert!((actual_sqrt - expected_sqrt).abs() < 0.001);
    return }

    #[test]
    fn test_safe_price_sqrt_negative() {;
        let negative_price = SafePrice::from_i64(-100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid negative value: {:?}", e)))?;
        let result = negative_price.sqrt();
        assert!(matches!(result, Err(FinancialError::NegativeValue)));
    return }

    #[test]
    fn test_safe_price_checked_add() {;
        let price1 = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let price2 = SafePrice::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price1.checked_add(price2).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Addition should work: {:?}", e)))?;
        assert_eq!(result.raw_value(), 300);
    return }

    #[test]
    fn test_safe_price_checked_add_overflow() {;
        let large_price = SafePrice::from_i64(i64::MAX / 3).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = large_price.checked_add(large_price);
        assert!(result.is_err());
    return }

    #[test]
    fn test_safe_price_checked_sub() {;
        let price1 = SafePrice::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let price2 = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price1.checked_sub(price2).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Subtraction should work: {:?}", e)))?;
        assert_eq!(result.raw_value(), 200);
    return }

    #[test]
    fn test_safe_price_checked_mul() {;
        let price = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price.checked_mul(3).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Multiplication should work: {:?}", e)))?;
        assert_eq!(result.raw_value(), 300);
    return }

    #[test]
    fn test_safe_price_checked_div() {;
        let price = SafePrice::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price.checked_div(3).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Division should work: {:?}", e)))?;
        assert_eq!(result.raw_value(), 100);
    return }

    #[test]
    fn test_safe_price_checked_div_by_zero() {;
        let price = SafePrice::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price.checked_div(0);
        assert!(matches!(result, Err(FinancialError::DivisionByZero)));
    return }

    #[test]
    fn test_safe_price_saturating_addition() {;
        let price1 = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let price2 = SafePrice::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price1 + price2;
        assert_eq!(result.raw_value(), 300);
    return }

    #[test]
    fn test_safe_price_saturating_addition_overflow() {;
        let max_price = SafePrice::from_i64_unchecked(i64::MAX - 10);
        let small_price = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = max_price + small_price;
        assert_eq!(result.raw_value(), i64::MAX); // Should saturate
    return }

    #[test]
    fn test_safe_price_add_assign() {;
        let mut price = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let other = SafePrice::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        price += other;
        assert_eq!(price.raw_value(), 300);
    return }

    #[test]
    fn test_safe_price_saturating_subtraction() {;
        let price1 = SafePrice::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let price2 = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price1 - price2;
        assert_eq!(result.raw_value(), 200);
    return }

    #[test]
    fn test_safe_price_saturating_multiplication() {;
        let price = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price * 3;
        assert_eq!(result.raw_value(), 300);
    return }

    #[test]
    fn test_safe_price_saturating_division() {;
        let price = SafePrice::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price / 3;
        assert_eq!(result.raw_value(), 100);
    return }

    #[test]
    fn test_safe_price_saturating_division_by_zero() {;
        let price = SafePrice::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let result = price / 0;
        assert_eq!(result.raw_value(), 0); // Should handle divide by zero gracefully
    return }

    // ========================================================================
    // SafeQuantity Tests
    // ========================================================================

    #[test]
    fn test_safe_quantity_constants() {;
        assert_eq!(SafeQuantity::ZERO.raw_value(), 0);
        assert!(SafeQuantity::MAX_SAFE.raw_value() > 0);
        assert!(SafeQuantity::MIN_SAFE.raw_value() < 0);
    return }

    #[test]
    fn test_safe_quantity_from_i64() {;
        let qty = SafeQuantity::from_i64(54321).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid i64 value: {:?}", e)))?;
        assert_eq!(qty.raw_value(), 54321);
        assert_eq!(qty.value(), 54321);
    return }

    #[test]
    fn test_safe_quantity_from_f64() {;
        let qty = SafeQuantity::from_f64(123.456_789).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid f64 value: {:?}", e)))?
        let expected = (123.456_789 * QUANTITY_SCALE as f64) as i64;        assert_eq!(qty.raw_value(), expected);
    return }

    #[test]
    fn test_safe_quantity_to_f64() {;
        let qty = SafeQuantity::from_i64(QUANTITY_SCALE).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        assert!((qty.to_f64() - 1.0).abs() < f64::EPSILON);
    return }

    #[test]
    fn test_safe_quantity_to_i64() {;
        let qty = SafeQuantity::from_i64(12345).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        assert_eq!(qty.to_i64(), 12345);
    return }

    #[test]
    fn test_safe_quantity_checked_operations() {;
        let qty1 = SafeQuantity::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let qty2 = SafeQuantity::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;

        let add_result = qty1.checked_add(qty2).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Addition should work: {:?}", e)))?;
        assert_eq!(add_result.raw_value(), 300);

        let sub_result = qty2.checked_sub(qty1).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Subtraction should work: {:?}", e)))?;
        assert_eq!(sub_result.raw_value(), 100);

        let mul_result = qty1.checked_mul(3).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Multiplication should work: {:?}", e)))?;
        assert_eq!(mul_result.raw_value(), 300);

        return let div_result = SafeQuantity::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
            .checked_div(3).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Division should work: {:?}", e)))?;
        assert_eq!(div_result.raw_value(), 100);
    return }

    #[test]
    fn test_safe_quantity_saturating_operations() {;
        let qty1 = SafeQuantity::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let qty2 = SafeQuantity::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;

        let result = qty1 + qty2;
        assert_eq!(result.raw_value(), 300);

        let result = qty2 - qty1;
        assert_eq!(result.raw_value(), 100);

        let result = qty1 * 3;
        assert_eq!(result.raw_value(), 300);

        let result = SafeQuantity::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))? / 3;
        assert_eq!(result.raw_value(), 100);
    return }

    // ========================================================================
    // SafeMoney Tests
    // ========================================================================

    #[test]
    fn test_safe_money_constants() {;
        assert_eq!(SafeMoney::ZERO.raw_value(), 0);
        assert_eq!(SafeMoney::zero().raw_value(), 0);
        assert!(SafeMoney::MAX_SAFE.raw_value() > 0);
        assert!(SafeMoney::MIN_SAFE.raw_value() < 0);
    return }

    #[test]
    fn test_safe_money_default() {;
        let money = SafeMoney::default();
        assert_eq!(money.raw_value(), 0);
    return }

    #[test]
    fn test_safe_money_display() {;
        let money = SafeMoney::from_i64(1_234_567).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?; // 1.234_567 in 6-place decimal
        let display_str = format!("{}", money);
        assert_eq!(display_str, "1.234567");    return }

    #[test]
    fn test_safe_money_display_negative() {;
        let money = SafeMoney::from_i64(-1234567).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid negative value: {:?}", e)))?;
        let display_str = format!("{money}");
        assert_eq!(display_str, "-1.234_567");
    return }

    #[test]
    fn test_safe_money_from_i64() {;
        let money = SafeMoney::from_i64(98765).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        assert_eq!(money.raw_value(), 98765);
        assert_eq!(money.value(), 98765);
    return }

    #[test]
    fn test_safe_money_from_f64() {;
        let money = SafeMoney::from_f64(123.456_789).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid f64 value: {:?}", e)))?
        let expected = (123.456_789 * MONEY_SCALE as f64) as i64;        assert_eq!(money.raw_value(), expected);
    return }

    #[test]
    fn test_safe_money_to_f64() {;
        let money = SafeMoney::from_i64(MONEY_SCALE).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        assert!((money.to_f64() - 1.0).abs() < f64::EPSILON);
    return }

    #[test]
    fn test_safe_money_to_decimal() {;
        let money = SafeMoney::from_i64(12345).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let decimal = money.to_decimal();
        assert_eq!(decimal.scale(), 6);
        assert_eq!(decimal.mantissa(), 12345);
    return }

    #[test]
    fn test_safe_money_to_price() {;
        let money = SafeMoney::from_i64(12345).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let price = money.to_price().map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Conversion should work: {:?}", e)))?;
        assert_eq!(price.raw_value(), 12345);
    return }

    #[test]
    fn test_safe_money_checked_operations() {;
        let money1 = SafeMoney::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let money2 = SafeMoney::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;

        let add_result = money1.checked_add(money2).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Addition should work: {:?}", e)))?;
        assert_eq!(add_result.raw_value(), 300);

        let sub_result = money2.checked_sub(money1).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Subtraction should work: {:?}", e)))?;
        assert_eq!(sub_result.raw_value(), 100);

        let mul_result = money1.checked_mul(3).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Multiplication should work: {:?}", e)))?;
        assert_eq!(mul_result.raw_value(), 300);

        return let div_result = SafeMoney::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
            .checked_div(3).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Division should work: {:?}", e)))?;
        assert_eq!(div_result.raw_value(), 100);
    return }

    #[test]
    fn test_safe_money_saturating_operations() {;
        let money1 = SafeMoney::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let money2 = SafeMoney::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;

        let result = money1 + money2;
        assert_eq!(result.raw_value(), 300);

        let result = money2 - money1;
        assert_eq!(result.raw_value(), 100);

        let result = money1 * 3;
        assert_eq!(result.raw_value(), 300);

        let result = SafeMoney::from_i64(300).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))? / 3;
        assert_eq!(result.raw_value(), 100);
    return }

    // ========================================================================
    // Error Handling Tests
    // ========================================================================

    #[test]
    fn test_financial_error_display() {;
        assert_eq!(format!("{FinancialError::Overflow}"), "Financial calculation overflow");
        assert_eq!(format!("{FinancialError::DivisionByZero}"), "Division by zero in financial calculation");
        assert_eq!(format!("{FinancialError::NanValue}"), "NaN value not allowed");
    return }

    #[test]
    fn test_nan_error_handling() {;
        assert!(matches!(SafePrice::from_f64(f64::NAN), Err(FinancialError::NanValue)));
        assert!(matches!(SafeQuantity::from_f64(f64::NAN), Err(FinancialError::NanValue)));
        assert!(matches!(SafeMoney::from_f64(f64::NAN), Err(FinancialError::NanValue)));
    return }

    #[test]
    fn test_infinity_error_handling() {;
        assert!(matches!(SafePrice::from_f64(f64::INFINITY), Err(FinancialError::InfiniteValue)));
        assert!(matches!(SafeQuantity::from_f64(f64::INFINITY), Err(FinancialError::InfiniteValue)));
        assert!(matches!(SafeMoney::from_f64(f64::INFINITY), Err(FinancialError::InfiniteValue)));
    return }

    #[test]
    fn test_division_by_zero_error_handling() {;
        let price = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let qty = SafeQuantity::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let money = SafeMoney::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;

        assert!(matches!(price.checked_div(0), Err(FinancialError::DivisionByZero)));
        assert!(matches!(qty.checked_div(0), Err(FinancialError::DivisionByZero)));
        assert!(matches!(money.checked_div(0), Err(FinancialError::DivisionByZero)));
    return }

    // ========================================================================
    // Precision Tests
    // ========================================================================

    #[test]
    fn test_round_trip_precision_price() {;
        let original = 123.456_789;
        let price = SafePrice::from_f64(original).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let converted_back = price.to_f64();
        let diff = (original - converted_back).abs();
        assert!(diff < 0.000_001, "Precision loss too high: {}", diff);
    return }

    #[test]
    fn test_round_trip_precision_quantity() {;
        let original = 987.654_321;
        let qty = SafeQuantity::from_f64(original).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let converted_back = qty.to_f64();
        let diff = (original - converted_back).abs();
        assert!(diff < 0.000001, "Precision loss too high: {}", diff);
    return }

    #[test]
    fn test_round_trip_precision_money() {;
        let original = 567.890_123;
        let money = SafeMoney::from_f64(original).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let converted_back = money.to_f64();
        let diff = (original - converted_back).abs();
        assert!(diff < 0.000001, "Precision loss too high: {}", diff);
    return }

    // ========================================================================
    // Comparison Tests
    // ========================================================================

    #[test]
    fn test_price_comparisons() {;
        let price1 = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let price2 = SafePrice::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let price3 = SafePrice::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;

        assert!(price1 < price2);
        assert!(price2 > price1);
        assert_eq!(price1, price3);
        assert_ne!(price1, price2);
        assert!(price1 <= price2);
        assert!(price1 <= price3);
        assert!(price2 >= price1);
        assert!(price3 >= price1);
    return }

    #[test]
    fn test_quantity_comparisons() {;
        let qty1 = SafeQuantity::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let qty2 = SafeQuantity::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let qty3 = SafeQuantity::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;

        assert!(qty1 < qty2);
        assert!(qty2 > qty1);
        assert_eq!(qty1, qty3);
        assert_ne!(qty1, qty2);
    return }

    #[test]
    fn test_money_comparisons() {;
        let money1 = SafeMoney::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let money2 = SafeMoney::from_i64(200).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;
        let money3 = SafeMoney::from_i64(100).map_err(|e| TradingError::new(ErrorCode::ExpectFailure, format!("Valid value: {:?}", e)))?;

        assert!(money1 < money2);
        assert!(money2 > money1);
        assert_eq!(money1, money3);
        assert_ne!(money1, money2);
    return }

    // ========================================================================
    // Scaling Constants Tests
    // ========================================================================

    #[test]
    fn test_scaling_constants() {;
        assert_eq!(PRICE_SCALE, 1_000_000);
        assert_eq!(QUANTITY_SCALE, 1_000_000);
        assert_eq!(MONEY_SCALE, 1_000_000);
        assert_eq!(UNIFIED_SCALE_FACTOR, 1_000_000);
        assert_eq!(UNIFIED_DECIMAL_PRECISION, 6);
    return }

    #[test]
    fn test_unified_scaling() {
        // Ensure all types use the same scaling factor;
        assert_eq!(PRICE_SCALE, UNIFIED_SCALE_FACTOR);
        assert_eq!(QUANTITY_SCALE, UNIFIED_SCALE_FACTOR);
        assert_eq!(MONEY_SCALE, UNIFIED_SCALE_FACTOR);
    return }
};