-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.

-- | Exact nonnegative protocol fractions, with positive denominators.
-- Numerators and denominators are unsigned 64-bit values. Input pairs remain
-- unreduced for serialization; equality and ordering compare numeric values.
--
-- @mkNonNegativeRational 577 10000@ constructs an exact execution price.
module Cometa.Protocol.Rational
  ( NonNegativeRational,
    mkNonNegativeRational,
    fromDouble,
    toDouble,
    numerator,
    denominator,
    toRational,
    encodeCbor,
    decodeCbor,
  )
where

-- IMPORTS --------------------------------------------------------------------

import Cometa.Error (Error (..))
import Cometa.Internal.ProtocolValues (NonNegativeRational, mkNonNegativeRational)
import qualified Cometa.Internal.ProtocolValues as Internal
import Data.ByteString (ByteString)
import Data.Word (Word64)
import Prelude hiding (toRational)

-- DEFINITIONS ----------------------------------------------------------------

-- | Convert a finite nonnegative Double using the native decimal-floor rule
-- on its fractional part, then add the whole part. Reduce that fractional pair
-- before adding the whole part, retaining native numerator/denominator choices.
-- Nonfinite, negative or out-of-uint64 whole parts return 'InvalidProtocolDouble'.
-- If the resulting exact numerator exceeds uint64, return
-- 'InvalidProtocolRational' instead of reproducing native unsigned overflow.
fromDouble :: Double -> Either Error NonNegativeRational
fromDouble :: Double -> Either Error NonNegativeRational
fromDouble Double
value
  | Double -> Bool
forall a. RealFloat a => a -> Bool
isNaN Double
value Bool -> Bool -> Bool
|| Double -> Bool
forall a. RealFloat a => a -> Bool
isInfinite Double
value Bool -> Bool -> Bool
|| Double
value Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
< Double
0 = Error -> Either Error NonNegativeRational
forall a b. a -> Either a b
Left Error
InvalidProtocolDouble
  | Integer
whole Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word64
forall a. Bounded a => a
maxBound :: Word64) = Error -> Either Error NonNegativeRational
forall a b. a -> Either a b
Left Error
InvalidProtocolDouble
  | Bool
otherwise =
      let fractionalNumerator :: Integer
fractionalNumerator = Double -> Integer
forall b. Integral b => Double -> b
forall a b. (RealFrac a, Integral b) => a -> b
floor ((Double
value Double -> Double -> Double
forall a. Num a => a -> a -> a
- Integer -> Double
forall a. Num a => Integer -> a
fromInteger Integer
whole) Double -> Double -> Double
forall a. Num a => a -> a -> a
* Double
1000000000000000)
          fractionalDenominator :: Integer
fractionalDenominator = Integer
1000000000000000
          divisor :: Integer
divisor = Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
gcd Integer
fractionalNumerator Integer
fractionalDenominator
          d :: Integer
d = Integer
fractionalDenominator Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`quot` Integer
divisor
          n :: Integer
n = Integer
fractionalNumerator Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`quot` Integer
divisor Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
whole Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
d
       in Integer -> Integer -> Either Error NonNegativeRational
mkNonNegativeRational Integer
n Integer
d
  where
    whole :: Integer
whole = Double -> Integer
forall b. Integral b => Double -> b
forall a b. (RealFrac a, Integral b) => a -> b
floor Double
value

-- | Convert numerator and denominator separately to Double and divide, matching
-- the native approximation without changing the stored exact pair.
toDouble :: NonNegativeRational -> Double
toDouble :: NonNegativeRational -> Double
toDouble NonNegativeRational
value = Word64 -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (NonNegativeRational -> Word64
numerator NonNegativeRational
value) Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Word64 -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (NonNegativeRational -> Word64
denominator NonNegativeRational
value)

-- | Original numerator, without fraction reduction.
numerator :: NonNegativeRational -> Word64
numerator :: NonNegativeRational -> Word64
numerator = NonNegativeRational -> Word64
Internal.rationalNumerator

-- | Original positive denominator, without fraction reduction.
denominator :: NonNegativeRational -> Word64
denominator :: NonNegativeRational -> Word64
denominator = NonNegativeRational -> Word64
Internal.rationalDenominator

-- | Exact numeric value, reduced by the standard Rational representation.
toRational :: NonNegativeRational -> Rational
toRational :: NonNegativeRational -> Rational
toRational = NonNegativeRational -> Rational
Internal.rationalValue

-- | Encode a definite-length ledger CBOR value with shortest integer encodings.
encodeCbor :: NonNegativeRational -> ByteString
encodeCbor :: NonNegativeRational -> ByteString
encodeCbor = (NonNegativeRational -> Encoding)
-> NonNegativeRational -> ByteString
forall a. (a -> Encoding) -> a -> ByteString
Internal.encodeBytes NonNegativeRational -> Encoding
Internal.encodeRational

-- | Decode exactly one ledger CBOR value. Invalid fields or trailing data return
-- 'Cometa.Error.InvalidProtocolCbor'. Nonminimal integers and indefinite arrays
-- are accepted; output encoding uses definite arrays and shortest integers.
decodeCbor :: ByteString -> Either Error NonNegativeRational
decodeCbor :: ByteString -> Either Error NonNegativeRational
decodeCbor = (forall s. Decoder s NonNegativeRational)
-> ByteString -> Either Error NonNegativeRational
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Internal.decodeBytes Decoder s NonNegativeRational
forall s. Decoder s NonNegativeRational
Internal.decodeRational