import { assert } from "../../assert.js";

/**
 * Second radiation constant.
 * Value is meters Kelvin (m*K).
 *
 * `c2 = (h*c) / (kb)`
 * @type {number}
 */
const PLANCK_C2 = 1.438776877e-2;

/**
 * Calculates the spectral radiance power of a black body for a given wavelength.
 * @param {number} lambda_m Wavelength in meters
 * @param {number} T Temperature in Kelvin
 * @returns {number} Relative spectral power
 */
export function planckian_radiance(lambda_m, T) {
    assert.isNumber(lambda_m, 'lambda_m');
    assert.notNaN(lambda_m, 'lambda_m');

    assert.isNumber(T, 'T');
    assert.notNaN(T, 'T');

    const lambda_T = lambda_m * T;
    const exponent = PLANCK_C2 / lambda_T;

    // Handle high exponents to prevent Math.exp from returning Infinity
    if (exponent > 80.0) { // exp(80) = ~5.5e34
        // this would pull denominator to extremely high values, effectively driving the result towards 0
        return 0.0;
    }

    const lambda_5 = Math.pow(lambda_m, 5);

    // This can be simplified to just (1/lambda_5) because the
    // rest of the numerator is a constant we are normalizing away.
    const radiance = (1.0 / lambda_5) / (Math.exp(exponent) - 1.0);

    return radiance;
}