-- 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 proportions from zero through one, inclusive.
-- Pairs retain their numerator and denominator; comparison is numeric.
--
-- @mkUnitInterval 2 3@ validates a two-thirds voting threshold.
module Cometa.UnitInterval
  ( UnitInterval,
    mkUnitInterval,
    fromDouble,
    toDouble,
    numerator,
    denominator,
    toRational,
    asNonNegativeRational,
    encodeCbor,
    decodeCbor,
  )
where

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

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

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

-- | Convert a finite number in @[0,1]@ using the native decimal-floor rule:
-- reduce @floor(value * 10^15) / 10^15@. This may round down and is not the
-- exact binary rational representation of the Double. NaN, infinities and values
-- outside the interval return 'InvalidUnitIntervalDouble'. Negative zero is zero.
fromDouble :: Double -> Either Error UnitInterval
fromDouble :: Double -> Either Error UnitInterval
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 Bool -> Bool -> Bool
|| Double
value Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
> Double
1 = Error -> Either Error UnitInterval
forall a b. a -> Either a b
Left Error
InvalidUnitIntervalDouble
  | Bool
otherwise =
      let n :: Integer
n = 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
* Double
1000000000000000)
          d :: Integer
d = Integer
1000000000000000
          divisor :: Integer
divisor = Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
gcd Integer
n Integer
d
       in Integer -> Integer -> Either Error UnitInterval
mkUnitInterval (Integer
n Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`quot` Integer
divisor) (Integer
d Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`quot` Integer
divisor)

-- | Approximate the fraction by converting its numerator and denominator
-- separately to Double and dividing, matching the native conversion. This can
-- differ from rounding an exact Rational once.
toDouble :: UnitInterval -> Double
toDouble :: UnitInterval -> Double
toDouble UnitInterval
value = Word64 -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (UnitInterval -> Word64
numerator UnitInterval
value) Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Word64 -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (UnitInterval -> Word64
denominator UnitInterval
value)

-- | Original unsigned numerator.
numerator :: UnitInterval -> Word64
numerator :: UnitInterval -> Word64
numerator = NonNegativeRational -> Word64
Internal.rationalNumerator (NonNegativeRational -> Word64)
-> (UnitInterval -> NonNegativeRational) -> UnitInterval -> Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UnitInterval -> NonNegativeRational
Internal.unitIntervalRational

-- | Original positive unsigned denominator.
denominator :: UnitInterval -> Word64
denominator :: UnitInterval -> Word64
denominator = NonNegativeRational -> Word64
Internal.rationalDenominator (NonNegativeRational -> Word64)
-> (UnitInterval -> NonNegativeRational) -> UnitInterval -> Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UnitInterval -> NonNegativeRational
Internal.unitIntervalRational

-- | Exact numeric proportion.
toRational :: UnitInterval -> Rational
toRational :: UnitInterval -> Rational
toRational = NonNegativeRational -> Rational
Internal.rationalValue (NonNegativeRational -> Rational)
-> (UnitInterval -> NonNegativeRational)
-> UnitInterval
-> Rational
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UnitInterval -> NonNegativeRational
Internal.unitIntervalRational

-- | Forget the upper bound while retaining the original fraction pair.
asNonNegativeRational :: UnitInterval -> NonNegativeRational
asNonNegativeRational :: UnitInterval -> NonNegativeRational
asNonNegativeRational = UnitInterval -> NonNegativeRational
Internal.unitIntervalRational

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

-- | 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 UnitInterval
decodeCbor :: ByteString -> Either Error UnitInterval
decodeCbor = (forall s. Decoder s UnitInterval)
-> ByteString -> Either Error UnitInterval
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Internal.decodeBytes Decoder s UnitInterval
forall s. Decoder s UnitInterval
Internal.decodeUnitInterval