///|
/// Raised when parsing or evaluating a `Decimal` breaks a rule.
#derive(Eq, Debug)
pub(all) suberror DecimalError {
  /// The text is not a valid Rego decimal or scientific number.
  InvalidDecimal(text~ : String)
  /// Division or remainder by zero.
  DivisionByZero
  /// Remainder requires integer operands.
  NonIntegerModulo
  /// Non-finite IEEE-754 float (NaN or Infinity).
  NonFiniteFloat
}

///|
pub impl Show for DecimalError with fn output(self, logger) {
  match self {
    InvalidDecimal(text~) => logger.write_string("invalid decimal `\{text}`")
    DivisionByZero => logger.write_string("division by zero")
    NonIntegerModulo => logger.write_string("modulo requires integer operands")
    NonFiniteFloat => logger.write_string("non-finite floating-point value")
  }
}

///|
/// Exact arbitrary-precision decimal number represented canonically as
/// `coeff * 10^exp`. Invariant: if `coeff == 0`, then `exp == 0`; otherwise
/// `coeff` is not divisible by 10. Structural equality therefore equals
/// mathematical equality (`1 == 1.0 == 1e0`).
#derive(Eq, Hash, Debug)
struct Decimal {
  coeff : @bigint.BigInt
  exp : Int32
}

///|
let big_zero : @bigint.BigInt = @bigint.BigInt::from_int(0)

///|
let big_one : @bigint.BigInt = @bigint.BigInt::from_int(1)

///|
let big_two : @bigint.BigInt = @bigint.BigInt::from_int(2)

///|
let big_five : @bigint.BigInt = @bigint.BigInt::from_int(5)

///|
let big_ten : @bigint.BigInt = @bigint.BigInt::from_int(10)

///|
fn pow10(n : Int32) -> @bigint.BigInt {
  if n <= 0 {
    return big_one
  }
  let mut result = big_one
  let mut base = big_ten
  let mut e = n
  while e > 0 {
    if (e & 1) == 1 {
      result = result * base
    }
    e = e >> 1
    if e > 0 {
      base = base * base
    }
  }
  result
}

///|
fn Decimal::normalize(coeff : @bigint.BigInt, exp : Int32) -> Decimal {
  if coeff == big_zero {
    return { coeff: big_zero, exp: 0, }
  }
  let mut c = coeff
  let mut e = exp
  while c % big_ten == big_zero {
    c = c / big_ten
    e += 1
  }
  { coeff: c, exp: e, }
}

///|
/// Zero (`0`).
pub fn Decimal::zero() -> Decimal {
  { coeff: big_zero, exp: 0, }
}

///|
/// One (`1`).
pub fn Decimal::one() -> Decimal {
  { coeff: big_one, exp: 0, }
}

///|
/// Constructs a `Decimal` from a 32-bit integer.
pub fn Decimal::from_int(n : Int32) -> Decimal {
  Decimal::normalize(@bigint.BigInt::from_int(n), 0)
}

///|
/// Constructs a `Decimal` from a 64-bit integer.
pub fn Decimal::from_int64(n : Int64) -> Decimal {
  Decimal::normalize(@bigint.BigInt::from_int64(n), 0)
}

///|
/// Constructs a `Decimal` from an arbitrary-precision `BigInt`.
pub fn Decimal::from_bigint(n : @bigint.BigInt) -> Decimal {
  Decimal::normalize(n, 0)
}

///|
/// Constructs a `Decimal` from a finite IEEE-754 `Double`.
pub fn Decimal::from_double(n : Double) -> Decimal raise DecimalError {
  if n.is_nan() || n.is_inf() {
    raise NonFiniteFloat
  }
  Decimal::Decimal(n.to_string())
}

///|
/// Parses a Rego numeric string (optional leading `-`, integer/fraction,
/// optional scientific exponent `e`/`E`) into a canonical `Decimal`.
pub fn Decimal::Decimal(text : String) -> Decimal raise DecimalError {
  let len = text.length()
  if len == 0 {
    raise InvalidDecimal(text~)
  }
  let mut i = 0
  let mut neg = false
  if text.code_unit_at(i).to_int() == 0x2D {
    neg = true
    i += 1
  } else if text.code_unit_at(i).to_int() == 0x2B {
    i += 1
  }
  if i >= len {
    raise InvalidDecimal(text~)
  }
  let digits = StringBuilder()
  let mut int_digits = 0
  while i < len {
    let c = text.code_unit_at(i).to_int()
    if c >= 0x30 && c <= 0x39 {
      digits.write_char(c.unsafe_to_char())
      int_digits += 1
      i += 1
    } else {
      break
    }
  }
  let mut frac_digits = 0
  if i < len && text.code_unit_at(i).to_int() == 0x2E {
    i += 1
    while i < len {
      let c = text.code_unit_at(i).to_int()
      if c >= 0x30 && c <= 0x39 {
        digits.write_char(c.unsafe_to_char())
        frac_digits += 1
        i += 1
      } else {
        break
      }
    }
    if frac_digits == 0 && int_digits == 0 {
      raise InvalidDecimal(text~)
    }
  }
  if int_digits == 0 && frac_digits == 0 {
    raise InvalidDecimal(text~)
  }
  let mut exp = -frac_digits
  if i < len {
    let ch = text.code_unit_at(i).to_int()
    if ch == 0x65 || ch == 0x45 {
      i += 1
      let mut exp_neg = false
      if i < len {
        let s = text.code_unit_at(i).to_int()
        if s == 0x2D {
          exp_neg = true
          i += 1
        } else if s == 0x2B {
          i += 1
        }
      }
      let exp_start = i
      let mut exp_val = 0
      while i < len {
        let c = text.code_unit_at(i).to_int()
        if c >= 0x30 && c <= 0x39 {
          if exp_val <= 32768 {
            exp_val = exp_val * 10 + (c - 0x30)
          }
          i += 1
        } else {
          break
        }
      }
      if i == exp_start || exp_val > 32768 {
        raise InvalidDecimal(text~)
      }
      exp += if exp_neg { -exp_val } else { exp_val }
    }
  }
  if i != len {
    raise InvalidDecimal(text~)
  }
  let raw_digits = digits.to_string()
  let mut coeff = @string.parse_bigint(raw_digits[:]) catch {
    _ => raise InvalidDecimal(text~)
  }
  if neg {
    coeff = -coeff
  }
  Decimal::normalize(coeff, exp)
}

///|
/// Reports whether this decimal is zero.
pub fn Decimal::is_zero(self : Decimal) -> Bool {
  self.coeff == big_zero
}

///|
/// Reports whether this decimal is strictly negative.
pub fn Decimal::is_negative(self : Decimal) -> Bool {
  self.coeff < big_zero
}

///|
/// Reports whether this decimal has no fractional part.
pub fn Decimal::is_integer(self : Decimal) -> Bool {
  self.exp >= 0
}

///|
/// Returns the exact `BigInt` value when this decimal is an integer.
pub fn Decimal::to_bigint(self : Decimal) -> @bigint.BigInt? {
  if self.exp < 0 {
    None
  } else if self.exp == 0 {
    Some(self.coeff)
  } else {
    Some(self.coeff * pow10(self.exp))
  }
}

///|
/// Returns the exact 64-bit integer value when this decimal is an integer in
/// the `Int64` range.
pub fn Decimal::to_int64(self : Decimal) -> Int64? {
  guard self.to_bigint() is Some(n) else { return None }
  let min64 = @bigint.BigInt::from_int64(-9223372036854775808L)
  let max64 = @bigint.BigInt::from_int64(9223372036854775807L)
  if n < min64 || n > max64 {
    return None
  }
  Some(n.to_int64())
}

///|
/// Returns the exact 32-bit integer value when this decimal is an integer in
/// the `Int32` range.
pub fn Decimal::to_int(self : Decimal) -> Int32? {
  guard self.to_int64() is Some(v) else { return None }
  if v < -2147483648L || v > 2147483647L {
    return None
  }
  Some(v.to_int())
}

///|
/// Converts this decimal to an approximate IEEE-754 `Double`.
pub fn Decimal::to_double(self : Decimal) -> Double {
  @string.parse_double(self.to_string()) catch {
    _ => 0.0
  }
}

///|
/// Negates this decimal.
pub fn Decimal::neg(self : Decimal) -> Decimal {
  if self.is_zero() {
    self
  } else {
    { coeff: -self.coeff, exp: self.exp, }
  }
}

///|
/// Absolute value of this decimal.
pub fn Decimal::abs(self : Decimal) -> Decimal {
  if self.is_negative() {
    self.neg()
  } else {
    self
  }
}

///|
fn bigint_digit_len(n : @bigint.BigInt) -> Int32 {
  let abs_n = if n < big_zero { -n } else { n }
  abs_n.to_string().length()
}

///|
/// Total mathematical order on `Decimal`.
pub impl Compare for Decimal with fn compare(self, other) {
  let s1 = if self.coeff < big_zero {
    -1
  } else if self.coeff > big_zero {
    1
  } else {
    0
  }
  let s2 = if other.coeff < big_zero {
    -1
  } else if other.coeff > big_zero {
    1
  } else {
    0
  }
  if s1 != s2 {
    return s1.compare(s2)
  }
  if s1 == 0 {
    return 0
  }
  // Fast magnitude check by decimal order (digit_len + exp).
  let mag1 = bigint_digit_len(self.coeff) + self.exp
  let mag2 = bigint_digit_len(other.coeff) + other.exp
  if mag1 != mag2 {
    return if s1 > 0 { mag1.compare(mag2) } else { mag2.compare(mag1) }
  }
  if self.exp == other.exp {
    self.coeff.compare(other.coeff)
  } else if self.exp > other.exp {
    let scaled = self.coeff * pow10(self.exp - other.exp)
    scaled.compare(other.coeff)
  } else {
    let scaled = other.coeff * pow10(other.exp - self.exp)
    self.coeff.compare(scaled)
  }
}

///|
pub extend Decimal with Compare::{compare}

///|
/// Exact decimal addition.
pub fn Decimal::add(self : Decimal, other : Decimal) -> Decimal {
  if self.is_zero() {
    return other
  }
  if other.is_zero() {
    return self
  }
  if self.exp == other.exp {
    Decimal::normalize(self.coeff + other.coeff, self.exp)
  } else if self.exp > other.exp {
    let scaled = self.coeff * pow10(self.exp - other.exp)
    Decimal::normalize(scaled + other.coeff, other.exp)
  } else {
    let scaled = other.coeff * pow10(other.exp - self.exp)
    Decimal::normalize(self.coeff + scaled, self.exp)
  }
}

///|
/// Exact decimal subtraction.
pub fn Decimal::sub(self : Decimal, other : Decimal) -> Decimal {
  self.add(other.neg())
}

///|
/// Exact decimal multiplication.
pub fn Decimal::mul(self : Decimal, other : Decimal) -> Decimal {
  if self.is_zero() || other.is_zero() {
    return Decimal::zero()
  }
  Decimal::normalize(self.coeff * other.coeff, self.exp + other.exp)
}

///|
/// Exact decimal division when terminating, else rounded to 50 significant
/// digits (half away from zero). Raises `DivisionByZero` when `other` is zero.
pub fn Decimal::div(
  self : Decimal,
  other : Decimal,
) -> Decimal raise DecimalError {
  if other.is_zero() {
    raise DivisionByZero
  }
  if self.is_zero() {
    return Decimal::zero()
  }
  let neg = self.is_negative() != other.is_negative()
  let num = if self.coeff < big_zero { -self.coeff } else { self.coeff }
  let den = if other.coeff < big_zero { -other.coeff } else { other.coeff }
  // Check if den divides evenly into a power of 10 (factors only of 2 and 5).
  let mut d = den
  let mut twos = 0
  while d % big_two == big_zero {
    d = d / big_two
    twos += 1
  }
  let mut fives = 0
  while d % big_five == big_zero {
    d = d / big_five
    fives += 1
  }
  if num % d == big_zero {
    let extra = if twos > fives { twos } else { fives }
    let scaled_num = num * pow10(extra)
    let mut q = scaled_num / den
    if neg {
      q = -q
    }
    return Decimal::normalize(q, self.exp - other.exp - extra)
  }
  // Non-terminating decimal: compute 50 significant digits with rounding.
  let sig_digits = 50
  let num_len = bigint_digit_len(num)
  let den_len = bigint_digit_len(den)
  let shift = sig_digits + den_len - num_len + 1
  let k = if shift > 0 { shift } else { 1 }
  let scaled_num = num * pow10(k)
  let mut q = scaled_num / den
  let rem = scaled_num % den
  if rem * big_two >= den {
    q = q + big_one
  }
  if neg {
    q = -q
  }
  Decimal::normalize(q, self.exp - other.exp - k)
}

///|
/// Integer remainder (`a % b`). Raises `DivisionByZero` if `other` is zero, or
/// `NonIntegerModulo` if either operand has a fractional part.
pub fn Decimal::rem(
  self : Decimal,
  other : Decimal,
) -> Decimal raise DecimalError {
  if other.is_zero() {
    raise DivisionByZero
  }
  guard (self.to_bigint(), other.to_bigint()) is (Some(a), Some(b)) else {
    raise NonIntegerModulo
  }
  Decimal::from_bigint(a % b)
}

///|
/// Floor to the greatest integer less than or equal to `self`.
pub fn Decimal::floor(self : Decimal) -> Decimal {
  if self.exp >= 0 {
    return self
  }
  let abs_c = if self.coeff < big_zero { -self.coeff } else { self.coeff }
  if bigint_digit_len(abs_c) < -self.exp {
    return if self.coeff < big_zero {
      Decimal::from_int(-1)
    } else {
      Decimal::zero()
    }
  }
  let scale = pow10(-self.exp)
  let q = self.coeff / scale
  let r = self.coeff % scale
  if r < big_zero {
    Decimal::from_bigint(q - big_one)
  } else {
    Decimal::from_bigint(q)
  }
}

///|
/// Ceiling to the smallest integer greater than or equal to `self`.
pub fn Decimal::ceil(self : Decimal) -> Decimal {
  if self.exp >= 0 {
    return self
  }
  let abs_c = if self.coeff < big_zero { -self.coeff } else { self.coeff }
  if bigint_digit_len(abs_c) < -self.exp {
    return if self.coeff > big_zero { Decimal::one() } else { Decimal::zero() }
  }
  let scale = pow10(-self.exp)
  let q = self.coeff / scale
  let r = self.coeff % scale
  if r > big_zero {
    Decimal::from_bigint(q + big_one)
  } else {
    Decimal::from_bigint(q)
  }
}

///|
/// Rounds to the nearest integer, half away from zero (matching OPA `round`).
pub fn Decimal::round(self : Decimal) -> Decimal {
  if self.exp >= 0 {
    return self
  }
  let abs_c = if self.coeff < big_zero { -self.coeff } else { self.coeff }
  if bigint_digit_len(abs_c) < -self.exp {
    return Decimal::zero()
  }
  let scale = pow10(-self.exp)
  let q = self.coeff / scale
  let r = self.coeff % scale
  let abs_r = if r < big_zero { -r } else { r }
  if abs_r * big_two >= scale {
    if self.coeff < big_zero {
      Decimal::from_bigint(q - big_one)
    } else {
      Decimal::from_bigint(q + big_one)
    }
  } else {
    Decimal::from_bigint(q)
  }
}

///|
/// Truncates this decimal toward zero, discarding any fractional digits.
pub fn Decimal::trunc(self : Decimal) -> Decimal {
  if self.exp >= 0 {
    return self
  }
  let abs_c = if self.coeff < big_zero { -self.coeff } else { self.coeff }
  if bigint_digit_len(abs_c) < -self.exp {
    return Decimal::zero()
  }
  let scale = pow10(-self.exp)
  Decimal::from_bigint(self.coeff / scale)
}

///|
/// Formats the decimal as canonical Rego/JSON numeric text.
pub fn Decimal::to_string(self : Decimal) -> String {
  if self.is_zero() {
    return "0"
  }
  let neg = self.is_negative()
  let abs_c = if neg { -self.coeff } else { self.coeff }
  let digits = abs_c.to_string()
  let dlen = digits.length()
  let buf = StringBuilder()
  if neg {
    buf.write_char('-')
  }
  if self.exp >= 0 {
    if self.exp <= 20 {
      buf.write_string(digits)
      for _ in 0.. 1 {
        buf.write_char('.')
        buf.write_string(digits[1:].to_owned())
      }
      buf.write_string("e+\{self.exp + dlen - 1}")
    }
  } else {
    let frac = -self.exp
    if frac < dlen {
      let split = dlen - frac
      buf.write_string(digits[:split].to_owned())
      buf.write_char('.')
      buf.write_string(digits[split:].to_owned())
    } else if frac - dlen <= 6 {
      buf.write_string("0.")
      for _ in 0..<(frac - dlen) {
        buf.write_char('0')
      }
      buf.write_string(digits)
    } else {
      let sci_exp = dlen - 1 - frac
      buf.write_string(digits[:1].to_owned())
      if dlen > 1 {
        buf.write_char('.')
        buf.write_string(digits[1:].to_owned())
      }
      buf.write_string("e\{sci_exp}")
    }
  }
  buf.to_string()
}

///|
pub impl Show for Decimal with fn output(self, logger) {
  logger.write_string(self.to_string())
}