// Demonstration: Earnings Margin Calculations
// This file demonstrates the calculation functions work correctly

fn calculate_gross_profit_margin(gross_profit: Option<f64>, revenue: Option<f64>) -> Option<f64> {
    let gross_profit = gross_profit?;
    let revenue = revenue?;
    (revenue.abs() > f64::EPSILON).then_some((gross_profit / revenue.abs()) * 100.0)
}

fn calculate_operating_margin(operating_profit: Option<f64>, revenue: Option<f64>) -> Option<f64> {
    let operating_profit = operating_profit?;
    let revenue = revenue?;
    (revenue.abs() > f64::EPSILON).then_some((operating_profit / revenue.abs()) * 100.0)
}

fn main() {
    println!("=== Earnings Margin Calculations Demo ===\n");

    // Microsoft FY2024 Data (in millions)
    let msft_revenue = 281_724.0;
    let msft_gross_profit = 193_893.0;
    let msft_operating_profit = 128_528.0;

    println!("Microsoft FY2024 Data:");
    println!("  Revenue: ${}M", msft_revenue as i64);
    println!("  Gross Profit: ${}M", msft_gross_profit as i64);
    println!("  Operating Profit: ${}M", msft_operating_profit as i64);
    println!();

    // Calculate Gross Profit Margin
    let gpm = calculate_gross_profit_margin(Some(msft_gross_profit), Some(msft_revenue));
    println!("Gross Profit Margin:");
    println!("  Calculated: {:.2}%", gpm.unwrap());
    println!("  Fiscal.ai: 68.8%");
    println!("  Match: {}", if gpm.unwrap().round() == 69.0 { "✓" } else { "✗" });
    println!();

    // Calculate Operating Margin
    let om = calculate_operating_margin(Some(msft_operating_profit), Some(msft_revenue));
    println!("Operating Margin:");
    println!("  Calculated: {:.2}%", om.unwrap());
    println!("  Fiscal.ai: 45.6%");
    println!("  Match: {}", if om.unwrap().round() == 46.0 { "✓" } else { "✗" });
    println!();

    // Edge Cases
    println!("=== Edge Cases ===\n");

    println!("1. Zero Revenue:");
    let zero_rev = calculate_gross_profit_margin(Some(100.0), Some(0.0));
    println!("   Result: {:?} (prevents division by zero)", zero_rev);
    println!();

    println!("2. Negative Profit (Loss):");
    let loss = calculate_gross_profit_margin(Some(-50.0), Some(100.0));
    println!("   Result: {:?} (handles losses correctly)", loss);
    println!();

    println!("3. Missing Data:");
    let missing = calculate_gross_profit_margin(Some(100.0), None);
    println!("   Result: {:?} (null propagation)", missing);
    println!();

    println!("=== All Calculations Working Correctly! ===");
}
