use sciforge::hub::domain::common::constants::SIGMA_SB;

pub fn has_glaciers() -> bool {
    false
}

pub fn has_polar_ice() -> bool {
    true
}

pub struct PolarIceDeposit {
    pub crater_name: &'static str,
    pub latitude_deg: f64,
    pub area_km2: f64,
    pub estimated_thickness_m: f64,
    pub temperature_k: f64,
}

impl PolarIceDeposit {
    pub fn volume_m3(&self) -> f64 {
        self.area_km2 * 1e6 * self.estimated_thickness_m
    }

    pub fn mass_kg(&self) -> f64 {
        let ice_density = 917.0;
        self.volume_m3() * ice_density
    }

    pub fn sublimation_rate(&self) -> f64 {
        let p_sat = ice_vapor_pressure(self.temperature_k);
        let m_h2o = 0.01802;
        let r = sciforge::hub::domain::common::constants::R_GAS;
        p_sat * (m_h2o / (2.0 * std::f64::consts::PI * r * self.temperature_k)).sqrt()
    }

    pub fn lifetime_years(&self) -> f64 {
        let ice_density = 917.0;
        let rate = self.sublimation_rate();
        if rate < 1e-30 {
            return f64::INFINITY;
        }
        ice_density * self.estimated_thickness_m / (rate * crate::SECONDS_PER_YEAR)
    }

    pub fn is_stable(&self) -> bool {
        self.temperature_k < 110.0
    }
}

pub fn known_ice_deposits() -> Vec<PolarIceDeposit> {
    vec![
        PolarIceDeposit {
            crater_name: "Prokofiev",
            latitude_deg: 85.8,
            area_km2: 3800.0,
            estimated_thickness_m: 2.0,
            temperature_k: 50.0,
        },
        PolarIceDeposit {
            crater_name: "Kandinsky",
            latitude_deg: 88.5,
            area_km2: 800.0,
            estimated_thickness_m: 1.5,
            temperature_k: 45.0,
        },
        PolarIceDeposit {
            crater_name: "Tolkien",
            latitude_deg: 88.8,
            area_km2: 500.0,
            estimated_thickness_m: 3.0,
            temperature_k: 40.0,
        },
        PolarIceDeposit {
            crater_name: "Chesterton",
            latitude_deg: 87.1,
            area_km2: 400.0,
            estimated_thickness_m: 1.0,
            temperature_k: 55.0,
        },
    ]
}

pub fn total_polar_ice_mass() -> f64 {
    crate::POLAR_ICE_MASS_KG
}

pub fn total_psr_area_km2() -> f64 {
    crate::PSR_AREA_KM2
}

pub fn radar_bright_crater_count() -> u32 {
    crate::RADAR_BRIGHT_CRATERS
}

pub fn psr_equilibrium_temp(latitude_deg: f64) -> f64 {
    let lat_rad = latitude_deg.to_radians();
    let thermal_input = 0.5 * (1.0 - lat_rad.sin());
    let flux = thermal_input * 5.0;
    (flux / (crate::SURFACE_EMISSIVITY * SIGMA_SB))
        .powf(0.25)
        .max(25.0)
}

fn ice_vapor_pressure(temp_k: f64) -> f64 {
    let a = 28.868;
    let b = 6132.9;
    (a - b / temp_k).exp()
}

pub fn ice_stability_depth(surface_temp_k: f64) -> f64 {
    if surface_temp_k < 110.0 {
        0.0
    } else {
        0.1 * (surface_temp_k - 110.0)
    }
}
