//! Quick empirical check of MSH smoothness near x=1.
//!
//! Run with: cargo test --release -p entropyk-components --lib -- test_msh_smoothness_empirical real_check --nocapture
use entropyk_components::heat_exchanger::two_phase_dp::{
    friedel_gradient, msh_gradient, FriedelInput,
};

#[test]
fn real_check() {
    // R134a-like at 5 °C, mass flux typical of DX evaporator at opening=1.
    let base = FriedelInput {
        mass_flux: 300.0,
        diameter: 0.0095,
        quality: 0.5,
        rho_liquid: 1290.0,
        rho_vapor: 17.4,
        mu_liquid: 250e-6,
        mu_vapor: 11e-6,
        sigma: 0.011,
    };

    let qualities = [
        0.10, 0.50, 0.80, 0.90, 0.95, 0.97, 0.99, 0.995, 0.999, 0.9999, 1.0,
    ];

    println!(
        "\n{:<10} {:<14} {:<14} {:<14}",
        "x", "MSH", "dMSH/dx", "Friedel"
    );
    let mut prev_msh: Option<f64> = None;
    let mut prev_x: Option<f64> = None;
    for &x in &qualities {
        let inp = FriedelInput { quality: x, ..base };
        let msh = msh_gradient(&inp);
        let fri = friedel_gradient(&inp);
        let dmsdh = match (prev_msh, prev_x) {
            (Some(pm), Some(px)) => (msh - pm) / (x - px),
            _ => f64::NAN,
        };
        println!("{:<10.5} {:<14.3} {:<14.3} {:<14.3}", x, msh, dmsdh, fri);
        prev_msh = Some(msh);
        prev_x = Some(x);
    }

    // Analytic derivative check: d/dx[linear·(1-x)^(1/3)] near x=1
    println!("\nAnalytic derivative of linear·(1-x)^(1/3) term:");
    let a: f64 =
        2.0 * 0.079 * (300.0_f64 * 0.0095 / 250e-6).powf(-0.25) * 300.0 * 300.0 / (0.0095 * 1290.0);
    let b: f64 =
        2.0 * 0.079 * (300.0_f64 * 0.0095 / 11e-6).powf(-0.25) * 300.0 * 300.0 / (0.0095 * 17.4);
    println!("  A = liquid-only gradient = {:.3} Pa/m", a);
    println!("  B = vapor-only gradient  = {:.3} Pa/m", b);
    println!("  Ratio B/A = {:.1}", b / a);
    for &x in &[0.9_f64, 0.95, 0.99, 0.999, 0.9999] {
        let linear = a + 2.0 * (b - a) * x;
        let term = linear * (1.0 - x).powf(1.0 / 3.0);
        // d/dx[linear·(1-x)^(1/3)] = 2(b-a)·(1-x)^(1/3) - (1/3)·linear·(1-x)^(-2/3)
        let d_term = 2.0 * (b - a) * (1.0 - x).powf(1.0 / 3.0)
            - (1.0 / 3.0) * linear * (1.0 - x).powf(-2.0 / 3.0);
        let d_total = d_term + 3.0 * b * x * x;
        println!(
            "  x={:.5}: term={:>10.2}  d(term)/dx={:>14.2}  d(MSH)/dx={:>14.2}",
            x, term, d_term, d_total
        );
    }
}
