use std::{
    cmp::Ordering,
    iter::Sum,
    ops::{Add, AddAssign, Div, Mul},
};

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use vecdb::{CheckedSub, Formattable, Pco};

use super::{Sats, VSize, Weight};

/// Fee rate in sat/vB
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, Pco, JsonSchema)]
#[schemars(
    example = &0.1,
    example = &1.0,
    example = &2.5,
    example = &10.14,
    example = &25.0,
    example = &302.11
)]
pub struct FeeRate(f64);

impl FeeRate {
    pub const MIN: Self = Self(0.1);

    pub const fn new(fr: f64) -> Self {
        Self(fr)
    }

    /// Round up to the nearest multiple of `nearest`.
    #[inline]
    pub fn ceil_to(self, nearest: Self) -> Self {
        Self((self.0 / nearest.0).ceil() * nearest.0)
    }

    /// Round to the nearest multiple of `nearest`.
    #[inline]
    pub fn round_to(self, nearest: Self) -> Self {
        Self((self.0 / nearest.0).round() * nearest.0)
    }

    /// Round to 3 decimal places via `(x * 1000).round() / 1000`.
    /// Divide-by-integer at the end is more numerically stable
    /// than `round_to(0.001)`'s closing `* 0.001`.
    #[inline]
    pub fn round_milli(self) -> Self {
        Self((self.0 * 1000.0).round() / 1000.0)
    }

    /// Arithmetic mean of two rates.
    #[inline]
    pub fn mean(a: Self, b: Self) -> Self {
        Self((a.0 + b.0) / 2.0)
    }
}

impl From<(Sats, VSize)> for FeeRate {
    #[inline]
    fn from((sats, vsize): (Sats, VSize)) -> Self {
        if sats.is_zero() {
            return Self(0.0);
        }
        let sats = u64::from(sats);
        let vsize = u64::from(vsize);
        if vsize == 0 {
            return Self(f64::NAN);
        }
        Self((sats * 1000).div_ceil(vsize) as f64 / 1000.0)
    }
}

impl From<(Sats, Weight)> for FeeRate {
    #[inline]
    fn from((sats, weight): (Sats, Weight)) -> Self {
        Self::from((sats, VSize::from(weight.to_vbytes_ceil())))
    }
}

impl From<f64> for FeeRate {
    #[inline]
    fn from(value: f64) -> Self {
        Self(value)
    }
}
impl From<FeeRate> for f64 {
    #[inline]
    fn from(value: FeeRate) -> Self {
        value.0
    }
}

impl Add for FeeRate {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl AddAssign for FeeRate {
    fn add_assign(&mut self, rhs: Self) {
        *self = *self + rhs
    }
}

impl Sum for FeeRate {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        Self(iter.map(|r| r.0).sum())
    }
}

impl Div<usize> for FeeRate {
    type Output = Self;
    fn div(self, rhs: usize) -> Self::Output {
        if rhs == 0 {
            Self(f64::NAN)
        } else {
            Self(self.0 / rhs as f64)
        }
    }
}

impl Div<f64> for FeeRate {
    type Output = Self;
    fn div(self, rhs: f64) -> Self::Output {
        Self(self.0 / rhs)
    }
}

impl Mul<f64> for FeeRate {
    type Output = Self;
    fn mul(self, rhs: f64) -> Self::Output {
        Self(self.0 * rhs)
    }
}

impl From<usize> for FeeRate {
    #[inline]
    fn from(value: usize) -> Self {
        Self(value as f64)
    }
}

impl PartialEq for FeeRate {
    fn eq(&self, other: &Self) -> bool {
        match (self.0.is_nan(), other.0.is_nan()) {
            (true, true) => true,
            (true, false) => false,
            (false, true) => false,
            (false, false) => self.0 == other.0,
        }
    }
}

impl Eq for FeeRate {}

#[allow(clippy::derive_ord_xor_partial_ord)]
impl PartialOrd for FeeRate {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

#[allow(clippy::derive_ord_xor_partial_ord)]
impl Ord for FeeRate {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self.0.is_nan(), other.0.is_nan()) {
            (true, true) => Ordering::Equal,
            (true, false) => Ordering::Less,
            (false, true) => Ordering::Greater,
            (false, false) => self.0.partial_cmp(&other.0).unwrap(),
        }
    }
}

impl CheckedSub for FeeRate {
    #[inline]
    fn checked_sub(self, rhs: Self) -> Option<Self> {
        let result = self.0 - rhs.0;
        if result.is_nan() {
            None
        } else {
            Some(Self(result))
        }
    }
}

impl std::fmt::Display for FeeRate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut buf = ryu::Buffer::new();
        let str = buf.format(self.0);
        f.write_str(str)
    }
}

impl Formattable for FeeRate {
    #[inline(always)]
    fn write_to(&self, buf: &mut Vec<u8>) {
        if self.0.is_finite() {
            let mut b = ryu::Buffer::new();
            buf.extend_from_slice(b.format(self.0).as_bytes());
        }
    }

    #[inline(always)]
    fn fmt_json(&self, buf: &mut Vec<u8>) {
        if self.0.is_finite() {
            self.write_to(buf);
        } else {
            buf.extend_from_slice(b"null");
        }
    }
}
