//! Risk Types Module
//!
//! Essential risk management types that were previously deleted but are still needed
//! by the risk management system. These types are used for risk validation,
//! compliance monitoring, and safety systems.
// #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)] // COMMENTED: Crate-level allows applied

use std::collections::HashMap;
use std::fmt;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tracing::warn;

// ELIMINATED: Re-exports removed to force explicit imports
use common::types::{OrderSide, OrderType, Price, Quantity, Symbol, Volume};
// Note: Side is an alias for OrderSide - using canonical OrderSide from trading_engine
// Note: Side is an alias for OrderSide in common crate - both are available

// TECHNICAL DEBT ELIMINATED - Use String directly instead of type aliases

/// Instrument identifier type
pub type InstrumentId = String;

/// Portfolio identifier type
pub type PortfolioId = String;

/// Strategy identifier type
pub type StrategyId = String;

// Use direct types from common::types instead of aliases:
//   - String for identifiers
//   - common::types::Symbol for instruments
//   - Direct enum types for portfolios and strategies

/// Risk severity levels for prioritizing responses
///
/// Used throughout the risk management system to categorize the urgency
/// and severity of risk events, violations, and alerts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum RiskSeverity {
    /// Low risk - informational only
    #[default]
    Low,
    /// Medium risk - requires monitoring
    Medium,
    /// High risk - requires immediate attention
    High,
    /// Critical risk - emergency response needed
    Critical,
}

/// Types of risk violations that can occur in the trading system
///
/// Each violation type represents a specific kind of risk limit breach
/// or compliance issue that requires different handling procedures.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ViolationType {
    /// Position size limit exceeded for an instrument
    PositionSizeExceeded,
    /// General position limit violation
    PositionLimit,
    /// Portfolio concentration risk threshold breached
    ConcentrationRisk,
    /// Maximum allowed drawdown percentage exceeded
    DrawdownLimit,
    /// Portfolio leverage ratio limit breached
    LeverageLimit,
    /// Value at Risk (`VaR`) calculation limit exceeded
    VarLimit,
    /// Portfolio leverage ratio exceeded safe thresholds
    LeverageExceeded,
    /// Total loss limit exceeded for portfolio or strategy
    LossLimitExceeded,
    /// Daily maximum loss limit exceeded
    DailyLossLimit,
    /// Total portfolio exposure limit exceeded
    ExposureLimit,
    /// Regulatory compliance rule violated
    RegulatoryViolation,
    /// Internal risk model threshold breached
    RiskModelBreach,
}

impl fmt::Display for ViolationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ViolationType::PositionSizeExceeded => write!(f, "Position Size Exceeded"),
            ViolationType::PositionLimit => write!(f, "Position Limit"),
            ViolationType::ConcentrationRisk => write!(f, "Concentration Risk"),
            ViolationType::DrawdownLimit => write!(f, "Drawdown Limit"),
            ViolationType::LeverageLimit => write!(f, "Leverage Limit"),
            ViolationType::VarLimit => write!(f, "VaR Limit"),
            ViolationType::LeverageExceeded => write!(f, "Leverage Exceeded"),
            ViolationType::LossLimitExceeded => write!(f, "Loss Limit Exceeded"),
            ViolationType::DailyLossLimit => write!(f, "Daily Loss Limit"),
            ViolationType::ExposureLimit => write!(f, "Exposure Limit"),
            ViolationType::RegulatoryViolation => write!(f, "Regulatory Violation"),
            ViolationType::RiskModelBreach => write!(f, "Risk Model Breach"),
        }
    }
}

/// Comprehensive risk violation details
///
/// Contains all information about a specific risk violation including
/// the type, severity, affected entities, and current values vs limits.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RiskViolation {
    /// Unique identifier for the violation
    pub id: String,
    /// Type of violation that occurred
    pub violation_type: ViolationType,
    /// Severity level of the violation
    pub severity: RiskSeverity,
    /// Brief human-readable description of the violation
    pub message: String,
    /// Detailed explanation of the violation and its implications
    pub description: String,
    /// Current value that triggered the violation (if applicable)
    pub current_value: Option<Price>,
    /// Maximum allowed value that was exceeded (if applicable)
    pub limit_value: Option<Price>,
    /// Instrument identifier involved in the violation (if applicable)
    pub instrument_id: Option<String>,
    /// Portfolio identifier involved in the violation (if applicable)
    pub portfolio_id: Option<String>,
    /// Strategy identifier involved in the violation (if applicable)
    pub strategy_id: Option<String>,
    /// Amount by which the limit was breached (if applicable)
    pub breach_amount: Option<Price>,
    /// Unix timestamp when the violation occurred
    pub timestamp: Option<i64>,
    /// Whether the violation has been acknowledged and resolved
    pub resolved: bool,
}

/// Result of a risk check operation on an order or trade
///
/// Represents the outcome when validating an order against risk limits,
/// including approval, rejection with reasons, or approval with warnings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RiskCheckResult {
    /// Order/trade approved without any issues
    Approved,
    /// Order/trade rejected due to risk violations
    Rejected {
        /// Primary reason for rejection
        reason: String,
        /// Highest severity level among violations
        severity: RiskSeverity,
        /// Detailed list of violations that caused rejection
        violations: Vec<RiskViolation>,
    },
    /// Order/trade approved but with risk warnings
    ApprovedWithWarnings {
        /// List of risk warnings to monitor
        warnings: Vec<RiskViolation>,
    },
}

/// Order information required for comprehensive risk validation
///
/// Contains all necessary order details to perform risk checks,
/// position limit validation, and compliance verification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OrderInfo {
    /// Unique identifier for this order
    pub order_id: String,
    /// Financial instrument symbol being traded
    pub symbol: Symbol,
    /// Internal instrument identifier for risk tracking
    pub instrument_id: String,
    /// Order side - buy or sell direction
    pub side: OrderSide,
    /// Number of shares/units to trade
    pub quantity: Quantity,
    /// Price per unit for the order
    pub price: Price,
    /// Type of order (market, limit, stop, etc.)
    pub order_type: Option<OrderType>,
    /// Portfolio this order belongs to (if applicable)
    pub portfolio_id: Option<String>,
    /// Trading strategy generating this order (if applicable)
    pub strategy_id: Option<String>,
    /// Account ID for per-account risk tracking (None falls back to "default" with warning)
    pub account_id: Option<String>,
}

/// Comprehensive Profit and Loss metrics for portfolio tracking
///
/// Contains all P&L calculations, drawdown metrics, and performance indicators
/// needed for risk monitoring and performance evaluation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PnLMetrics {
    /// Unique identifier of the portfolio these metrics apply to
    pub portfolio_id: String,
    /// Realized profit/loss from closed positions
    pub realized_pnl: Price,
    /// Unrealized profit/loss from open positions
    pub unrealized_pnl: Price,
    /// Total unrealized P&L across all open positions
    pub total_unrealized_pnl: Price,
    /// Total profit/loss (realized + unrealized)
    pub total_pnl: Price,
    /// Profit/loss for the current trading day
    pub daily_pnl: Price,
    /// Total P&L since portfolio inception
    pub inception_pnl: Price,
    /// Maximum drawdown from highest portfolio value
    pub max_drawdown: Price,
    /// Current drawdown as percentage from peak
    pub current_drawdown_pct: f64,
    /// Highest portfolio value achieved (high water mark)
    pub high_water_mark: Price,
    /// Return on investment as percentage of initial capital
    pub roi_pct: f64,
    /// Unix timestamp when these metrics were calculated
    pub timestamp: i64,
}

/// Comprehensive risk position information for an instrument
///
/// Tracks position details, market values, P&L, and risk metrics
/// for real-time risk monitoring and portfolio management.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RiskPosition {
    /// Unique identifier of the financial instrument
    pub instrument_id: String,
    /// Current position size (positive for long, negative for short)
    pub quantity: Quantity,
    /// Volume-weighted average entry price
    pub avg_price: Price,
    /// Current market price of the instrument
    pub current_price: Price,
    /// Current market value of the entire position
    pub market_value: Price,
    /// Unrealized profit/loss at current market price
    pub unrealized_pnl: Price,
    /// Realized profit/loss from partial closes
    pub realized_pnl: Price,
    /// Portfolio identifier that owns this position
    pub portfolio_id: String,
    /// Strategy identifier that created this position (if applicable)
    pub strategy_id: Option<String>,
    /// Detailed position information for internal tracking
    pub position: Position,
}

/// Detailed position information for internal tracking and calculations
///
/// Contains position metrics in floating-point format for mathematical
/// operations and compatibility with legacy systems.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Position {
    /// Trading symbol or instrument identifier
    pub symbol: String,
    /// Position quantity in floating-point (positive for long, negative for short)
    pub quantity: f64,
    /// Current market price as floating-point value
    pub market_price: f64,
    /// Total market value of position (quantity × `market_price`)
    pub market_value: f64,
    /// Volume-weighted average cost basis as floating-point
    pub average_cost: f64,
    /// Volume-weighted average price in Price format
    pub average_price: Price,
    /// Unrealized profit/loss as floating-point value
    pub unrealized_pnl: f64,
    /// Realized profit/loss as floating-point value
    pub realized_pnl: f64,
    /// Unix timestamp of the last position update
    pub last_updated: i64,
}

impl RiskPosition {
    /// Create a new risk position
    #[must_use]
    pub fn new(
        instrument_id: String,
        quantity: Quantity,
        avg_price: Price,
        current_price: Price,
        portfolio_id: String,
    ) -> Self {
        // Calculate market value with overflow protection
        let market_value = {
            let qty_i64 = quantity.raw_value() as i64;
            let price_i64 = current_price.raw_value() as i64;

            if let Some(result) = qty_i64.checked_mul(price_i64) {
                Price::new(result as f64).unwrap_or_default()
            } else {
                warn!(
                    "Arithmetic overflow in market value calculation: quantity={} * price={}",
                    qty_i64, price_i64
                );
                Price::ZERO
            }
        };

        // Safe calculation to avoid overflow with checked arithmetic
        let price_diff = current_price.raw_value() as i64 - avg_price.raw_value() as i64;
        let quantity_i64 = quantity.raw_value() as i64;

        let pnl_raw = if let Some(result) = quantity_i64.checked_mul(price_diff) {
            result as f64
        } else {
            warn!(
                "Arithmetic overflow in position PnL calculation: quantity={} * price_diff={}",
                quantity_i64, price_diff
            );
            0.0
        };

        let unrealized_pnl = Price::new(pnl_raw.abs()).unwrap_or_else(|e| {
            warn!("Failed to calculate unrealized PnL for position: {}", e);
            Price::ZERO
        });

        RiskPosition {
            instrument_id: instrument_id.clone(),
            quantity,
            avg_price,
            current_price,
            market_value,
            unrealized_pnl,
            realized_pnl: Price::ZERO,
            portfolio_id,
            strategy_id: None,
            position: Position {
                symbol: instrument_id,
                quantity: quantity.raw_value() as f64,
                market_price: current_price.raw_value() as f64,
                market_value: market_value.raw_value() as f64,
                average_cost: avg_price.raw_value() as f64,
                average_price: avg_price,
                unrealized_pnl: unrealized_pnl.raw_value() as f64,
                realized_pnl: 0.0,
                last_updated: Utc::now().timestamp(),
            },
        }
    }

    /// Update position with new market data
    pub fn update_position(&mut self, volume: Quantity, avg_cost: Price, market_value: Price) {
        self.quantity = volume;
        self.avg_price = avg_cost;
        self.market_value = market_value;
        self.position.quantity = volume.to_f64();
        self.position.market_value = market_value.raw_value() as f64;
        self.position.average_cost = avg_cost.raw_value() as f64;
        self.position.average_price = avg_cost;
        self.position.last_updated = Utc::now().timestamp();

        // Recalculate unrealized P&L with overflow protection
        let price_diff = self.current_price.raw_value() as i64 - self.avg_price.raw_value() as i64;
        let quantity_i64 = self.quantity.raw_value() as i64;

        let pnl_raw = if let Some(result) = quantity_i64.checked_mul(price_diff) {
            result as f64
        } else {
            warn!(
                "Arithmetic overflow in position update: quantity={} * price_diff={}",
                quantity_i64, price_diff
            );
            0.0
        };

        self.unrealized_pnl = Price::new(pnl_raw.abs()).unwrap_or_else(|e| {
            warn!("Failed to update unrealized PnL: {}", e);
            Price::ZERO
        });

        // Update position unrealized P&L
        self.position.unrealized_pnl = self.unrealized_pnl.raw_value() as f64;
    }
}

/// Market data snapshot for risk calculations and pricing
///
/// Contains current market prices, volume, and volatility data
/// needed for real-time risk assessment and position valuation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MarketData {
    /// Unique identifier of the financial instrument
    pub instrument_id: String,
    /// Highest price buyers are willing to pay
    pub bid: Price,
    /// Lowest price sellers are willing to accept
    pub ask: Price,
    /// Price of the most recent trade
    pub last_price: Price,
    /// Most recent transaction price (alias for `last_price`)
    pub last: Price,
    /// Total trading volume for the current day
    pub volume: Volume,
    /// Unix timestamp when this market data was captured
    pub timestamp: i64,
    /// Implied or historical volatility measure (if available)
    pub volatility: Option<f64>,
}

/// Risk configuration parameters for a specific trading symbol
///
/// Defines position limits, concentration thresholds, and risk multipliers
/// that apply to trading in a particular financial instrument.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SymbolRiskConfig {
    /// Trading symbol this configuration applies to
    pub symbol: Symbol,
    /// Maximum allowed position size in shares/units
    pub max_position: Quantity,
    /// Maximum daily notional trading value
    pub max_daily_notional: Price,
    /// Maximum position value in USD equivalent
    pub max_position_value_usd: f64,
    /// Maximum portfolio concentration percentage for this symbol
    pub max_concentration_pct: f64,
    /// Risk multiplier applied to `VaR` calculations for this symbol
    pub risk_multiplier: f64,
    /// Volatility threshold above which additional risk controls apply
    pub volatility_threshold: f64,
}

/// Comprehensive position limits for portfolio risk management
///
/// Defines maximum exposure limits across different dimensions including
/// per-instrument limits, portfolio-wide limits, and concentration thresholds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PositionLimits {
    /// Maximum position size allowed per individual instrument
    pub max_position_per_instrument: HashMap<String, Quantity>,
    /// Maximum total value allowed for the entire portfolio
    pub max_portfolio_value: Price,
    /// Maximum leverage ratio (total exposure / capital)
    pub max_leverage: f64,
    /// Maximum concentration percentage per instrument of total portfolio
    pub max_concentration_pct: f64,
    /// Global position limit summed across all instruments
    pub global_limit: Price,
}

/// Stress testing scenario definition for portfolio risk assessment
///
/// Defines market shocks, volatility changes, and correlation adjustments
/// to test portfolio resilience under adverse market conditions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StressScenario {
    /// Unique identifier for this stress test scenario
    pub id: String,
    /// Human-readable name describing the scenario
    pub name: String,
    /// Price shock percentages to apply per instrument
    pub price_shocks: HashMap<String, f64>,
    /// Market shocks (alternative name for `price_shocks`)
    pub market_shocks: HashMap<String, f64>,
    /// Global volatility multiplier to apply across all instruments
    pub volatility_multiplier: f64,
    /// Instrument-specific volatility multipliers
    pub volatility_multipliers: HashMap<String, f64>,
    /// Changes to correlation coefficients between instruments
    pub correlation_changes: HashMap<String, f64>,
    /// Additional correlation adjustments to apply
    pub correlation_adjustments: HashMap<String, f64>,
    /// Liquidity haircuts to apply per instrument (reduced bid/ask)
    pub liquidity_haircuts: HashMap<String, f64>,
}

/// Results from executing a stress test scenario on a portfolio
///
/// Contains before/after portfolio values, P&L impacts, risk breaches,
/// and performance metrics from stress testing analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StressTestResult {
    /// The stress test scenario that was executed
    pub scenario: StressScenario,
    /// Unique identifier of the executed scenario
    pub scenario_id: String,
    /// Portfolio that was stress tested
    pub portfolio_id: String,
    /// Portfolio value before applying stress conditions
    pub pre_stress_value: Price,
    /// Portfolio value after applying stress conditions
    pub post_stress_value: Price,
    /// Projected portfolio value under the stress scenario
    pub stressed_portfolio_value: Price,
    /// Projected profit/loss under stress conditions
    pub stressed_pnl: Price,
    /// Change in P&L due to stress (difference from baseline)
    pub stress_pnl: Price,
    /// Stress P&L impact as percentage of portfolio value
    pub stress_pnl_percentage: f64,
    /// Whether `VaR` limits were breached during stress test
    pub var_breach: bool,
    /// List of risk limits that were breached during stress test
    pub limit_breaches: Vec<String>,
    /// Amount of liquidity shortfall identified during stress test
    pub liquidity_shortfall: Price,
    /// Instrument that experienced the largest loss during stress test
    pub max_loss_instrument: Option<String>,
    /// Largest single instrument loss during stress test
    pub max_loss: Price,
    /// Time taken to execute the stress test in milliseconds
    pub execution_time_ms: u64,
    /// UTC timestamp when the stress test was performed
    pub timestamp: DateTime<Utc>,
    /// Maximum drawdown observed under stress conditions
    pub max_drawdown: Price,
    /// Additional risk metrics calculated under stress conditions
    pub risk_metrics: HashMap<String, f64>,
}

/// Scope of kill switch activation for emergency trading halts
///
/// Defines the breadth of impact when a kill switch is triggered,
/// from global shutdown to specific instrument or strategy halts.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum KillSwitchScope {
    /// Stop all trading activity across the entire system
    Global,
    /// Stop trading for a specific portfolio only
    Portfolio(String),
    /// Stop trading for a specific strategy only
    Strategy(String),
    /// Stop trading for a specific financial instrument only
    Instrument(String),
    /// Stop trading for a specific trading symbol only
    Symbol(String),
    /// Stop trading for a specific account only
    Account(String),
}

/// Types of events that can trigger circuit breaker activation
///
/// Circuit breakers automatically halt trading when specific risk thresholds
/// are breached to prevent further losses or limit violations.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CircuitBreakerEvent {
    /// Portfolio drawdown limit has been breached
    DrawdownBreach {
        /// Current drawdown percentage from peak
        current_drawdown: f64,
        /// Maximum allowed drawdown percentage
        limit: f64,
    },
    /// Value at Risk (`VaR`) limit has been breached
    VarBreach {
        /// Current `VaR` calculation result
        current_var: f64,
        /// Maximum allowed `VaR` value
        limit: f64,
    },
    /// Position size limit has been breached for an instrument
    PositionBreach {
        /// Instrument that breached position limits
        instrument_id: String,
        /// Current position size that exceeded limits
        current_position: Quantity,
        /// Maximum allowed position size
        limit: Quantity,
    },
    /// Manual intervention is required to resolve a risk issue
    ManualIntervention {
        /// Detailed reason why manual intervention is needed
        reason: String,
    },
}

/// Configuration for drawdown-based alert thresholds
///
/// Defines progressive alert levels as portfolio drawdown increases,
/// enabling early warning and escalation procedures.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DrawdownAlertConfig {
    /// Drawdown percentage that triggers warning alerts
    pub warning_threshold: f64,
    /// Drawdown percentage that triggers critical alerts
    pub critical_threshold: f64,
    /// Drawdown percentage that triggers emergency response
    pub emergency_threshold: f64,
    /// Specific portfolio this configuration applies to (if any)
    pub portfolio_id: Option<String>,
    /// Whether drawdown alerting is currently enabled
    pub enabled: bool,
}

// Use Price directly from common::types
/// Compliance audit entry for regulatory tracking and reporting
///
/// Records all significant events, decisions, and actions for compliance
/// monitoring, regulatory reporting, and audit trail maintenance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Unique identifier for this audit entry
    pub id: String,
    /// Unix timestamp when the audited event occurred
    pub timestamp: i64,
    /// Classification of the audited event
    pub event_type: String,
    /// Detailed description of what occurred
    pub description: String,
    /// User ID or system component that triggered the event
    pub actor: String,
    /// Specific user identifier if applicable
    pub user_id: Option<String>,
    /// Financial instrument involved in the event (if applicable)
    pub instrument_id: Option<String>,
    /// Portfolio involved in the event (if applicable)
    pub portfolio_id: Option<String>,
    /// Structured event data as key-value pairs
    pub data: HashMap<String, String>,
    /// Additional metadata and context information
    pub metadata: HashMap<String, String>,
}

/// Compliance rule type categorization for dynamic rule evaluation
///
/// Defines the type of compliance check to perform, enabling
/// dynamic rule configuration and hot-reload capabilities.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ComplianceRuleType {
    /// Position size and turnover limits
    PositionLimit,
    /// Market abuse and manipulation detection
    MarketAbuse,
    /// Client suitability and appropriateness
    ClientSuitability,
    /// Best execution requirements
    BestExecution,
    /// Portfolio concentration risk
    ConcentrationRisk,
    /// Leverage and margin limits
    LeverageLimit,
    /// Capital adequacy requirements
    CapitalAdequacy,
    /// Regulatory reporting obligations
    RegulatoryReporting,
    /// Custom user-defined rule
    Custom,
}

/// Definition of a regulatory compliance rule with dynamic configuration
///
/// Enhanced compliance rule structure supporting database-backed
/// configuration and hot-reload capabilities through `PostgreSQL` NOTIFY/LISTEN.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ComplianceRule {
    /// Unique identifier for this compliance rule
    pub id: String,
    /// Human-readable name of the compliance rule
    pub name: String,
    /// Detailed description of the compliance requirement
    pub description: String,
    /// Type of compliance rule for categorization
    pub rule_type: ComplianceRuleType,
    /// Whether this rule is currently being enforced
    pub active: bool,
    /// Version number for audit trail
    pub version: i32,
    /// Severity level when this rule is violated
    pub severity: RiskSeverity,
    /// Priority for rule evaluation (0-100, higher = higher priority)
    pub priority: i32,
    /// Flexible rule parameters as JSON (thresholds, limits, etc.)
    pub parameters: serde_json::Value,
    /// Regulatory framework (`MiFID` II, Basel III, etc.)
    pub regulatory_framework: Option<String>,
    /// Specific regulatory reference (Article, Section, etc.)
    pub regulatory_reference: Option<String>,
}

/// Overall compliance configuration for the trading system
///
/// Contains all compliance rules, position limits, and audit settings
/// required for regulatory compliance monitoring.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ComplianceConfig {
    /// Collection of all compliance rules to be enforced
    pub rules: Vec<ComplianceRule>,
    /// Position limits for compliance monitoring
    pub position_limits: PositionLimits,
    /// Number of days to retain audit records for compliance
    pub audit_retention_days: u32,
    /// Market abuse detection threshold
    pub market_abuse_threshold: Option<Price>,
    /// Large exposure threshold for regulatory reporting
    pub large_exposure_threshold: Price,
}

/// Types of compliance warnings that can be issued
///
/// Categorizes different kinds of compliance issues that require
/// attention but may not constitute immediate violations.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ComplianceWarningType {
    /// Position size is approaching regulatory or internal limits
    PositionApproachingLimit,
    /// Portfolio concentration risk is building up
    ConcentrationRisk,
    /// Unusual or suspicious trading pattern detected
    UnusualPattern,
    /// Regulatory reporting or compliance deadline approaching
    RegulatoryDeadline,
    /// Issue with client classification or suitability
    ClientClassificationIssue,
    /// Risk of not achieving best execution for clients
    BestExecutionRisk,
    /// Capital adequacy ratios approaching minimum thresholds
    CapitalAdequacyLow,
    /// Leverage ratios approaching maximum allowed levels
    LeverageRatioHigh,
    /// Approaching various regulatory limits
    NearLimit,
    /// Large exposure requiring regulatory attention
    LargeExposure,
}

/// Compliance warning issued when approaching regulatory limits
///
/// Contains detailed information about potential compliance issues
/// that require monitoring or corrective action.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ComplianceWarning {
    /// Unique identifier for this compliance warning
    pub id: String,
    /// Category of compliance warning
    pub warning_type: ComplianceWarningType,
    /// Severity level of this warning
    pub severity: WarningSeverity,
    /// Brief warning message for display
    pub message: String,
    /// Detailed explanation of the compliance concern
    pub description: String,
    /// Financial instrument related to this warning (if applicable)
    pub instrument_id: Option<String>,
    /// Portfolio related to this warning (if applicable)
    pub portfolio_id: Option<String>,
    /// Reference to applicable regulation or rule
    pub regulatory_reference: String,
    /// Suggested corrective action to address the warning
    pub recommended_action: String,
    /// UTC timestamp when this warning was generated
    pub timestamp: DateTime<Utc>,
}

/// Types of regulatory flags for special handling requirements
///
/// Identifies transactions or positions that require special regulatory
/// treatment, reporting, or monitoring procedures.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RegulatoryFlagType {
    /// Pattern day trader rules and restrictions apply
    PatternDayTrader,
    /// Position exceeds thresholds requiring regulatory reporting
    RegulatorReporting,
    /// General regulatory reporting is required
    ReportingRequired,
    /// Position size requires public disclosure
    LargePosition,
    /// Transaction crosses national borders
    CrossBorder,
    /// Enhanced market risk monitoring required
    MarketRisk,
    /// High frequency trading activity detected
    HighFrequencyTrading,
    /// Algorithmic trading system in use
    AlgorithmicTrading,
}

/// Regulatory flag indicating special handling requirements
///
/// Attached to positions or transactions that require special
/// regulatory treatment, monitoring, or reporting procedures.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RegulatoryFlag {
    /// Category of regulatory requirement
    pub flag_type: RegulatoryFlagType,
    /// Name of the applicable regulation or rule
    pub regulation: String,
    /// Detailed description of the regulatory requirement
    pub description: String,
    /// Whether immediate compliance action is required
    pub action_required: bool,
    /// Deadline for compliance action (if applicable)
    pub deadline: Option<DateTime<Utc>>,
}

/// Severity levels for warnings and alerts
///
/// Provides graduated severity classification for warnings,
/// enabling appropriate response and escalation procedures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum WarningSeverity {
    /// Low priority warning requiring routine attention
    Low,
    /// Medium priority warning requiring timely attention
    Medium,
    /// High priority warning requiring immediate attention
    High,
    /// Informational notice for awareness
    Info,
    /// General warning requiring monitoring
    Warning,
    /// Error condition requiring corrective action
    Error,
    /// Critical error requiring immediate intervention
    Critical,
}

impl Default for PnLMetrics {
    fn default() -> Self {
        // SAFE: Zero values for PnL metrics are valid defaults for new portfolios
        // Unlike position prices, zero PnL represents "no profit/loss yet"
        PnLMetrics {
            portfolio_id: String::new(),
            realized_pnl: Price::ZERO,
            unrealized_pnl: Price::ZERO,
            total_unrealized_pnl: Price::ZERO,
            total_pnl: Price::ZERO,
            daily_pnl: Price::ZERO,
            inception_pnl: Price::ZERO,
            max_drawdown: Price::ZERO,
            current_drawdown_pct: 0.0,
            high_water_mark: Price::ZERO,
            roi_pct: 0.0,
            timestamp: Utc::now().timestamp(),
        }
    }
}

impl Default for PositionLimits {
    fn default() -> Self {
        PositionLimits {
            max_position_per_instrument: HashMap::new(),
            max_portfolio_value: Price::new(1_000_000.0).unwrap_or_default(),
            max_leverage: 10.0,
            max_concentration_pct: 20.0,
            global_limit: Price::new(10_000_000.0).unwrap_or_default(),
        }
    }
}
