-- 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.

-- | Immutable advanced value snapshots retaining native stored-state details.
-- Ordinary "Cometa.Value" is a normalized quantity bundle; this module keeps
-- explicit zero assets, repeated names and empty policy groups. These snapshots
-- are not transaction outputs and do not establish ledger validity.
--
-- @
-- import qualified Cometa.Value.Raw as Raw
--
-- emptySnapshot = Raw.mkSnapshot 0 []
-- @
module Cometa.Value.Raw
  ( Snapshot,
    mkSnapshot,
    coin,
    assets,
    fromValue,
    toValue,
  )
where

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

import Cometa.AssetId (AssetId (Ada, Native))
import Cometa.AssetName (AssetName)
import qualified Cometa.AssetName as Name
import Cometa.Error (Error (InvalidValueQuantity))
import Cometa.PolicyId (PolicyId)
import qualified Cometa.Value as Value
import Control.Monad (unless)
import qualified Data.ByteString as B
import Data.Int (Int64)
import Data.List (sortOn)
import qualified Data.Map.Strict as Map

-- TYPES ----------------------------------------------------------------------

-- | Signed coin plus raw native-asset associations. Equality compares every
-- stored entry, including zero quantities, repeated names and empty groups.
-- Values are Haskell-owned immutable snapshots; retaining one preserves it when
-- another snapshot is assembled or converted. No cloning allocation is needed.
data Snapshot = Snapshot !Integer ![(PolicyId, [(AssetName, Integer)])]
  deriving (Snapshot -> Snapshot -> Bool
(Snapshot -> Snapshot -> Bool)
-> (Snapshot -> Snapshot -> Bool) -> Eq Snapshot
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Snapshot -> Snapshot -> Bool
== :: Snapshot -> Snapshot -> Bool
$c/= :: Snapshot -> Snapshot -> Bool
/= :: Snapshot -> Snapshot -> Bool
Eq, Int -> Snapshot -> ShowS
[Snapshot] -> ShowS
Snapshot -> String
(Int -> Snapshot -> ShowS)
-> (Snapshot -> String) -> ([Snapshot] -> ShowS) -> Show Snapshot
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Snapshot -> ShowS
showsPrec :: Int -> Snapshot -> ShowS
$cshow :: Snapshot -> String
show :: Snapshot -> String
$cshowList :: [Snapshot] -> ShowS
showList :: [Snapshot] -> ShowS
Show)

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

-- | Validate signed 64-bit coin and asset quantities, returning
-- 'InvalidValueQuantity' on overflow. Policies sort by hash bytes; repeated
-- policy keys use the last supplied group. Names sort stably by byte length,
-- then bytes, retaining repeated names in their supplied tie order. Explicit
-- zeros and empty groups remain. The signed coin is raw accounting state;
-- negative coin is not a valid transaction-output amount.
mkSnapshot :: Integer -> [(PolicyId, [(AssetName, Integer)])] -> Either Error Snapshot
mkSnapshot :: Integer
-> [(PolicyId, [(AssetName, Integer)])] -> Either Error Snapshot
mkSnapshot Integer
lovelace [(PolicyId, [(AssetName, Integer)])]
groups = do
  Integer -> Either Error ()
bounded Integer
lovelace
  ((PolicyId, [(AssetName, Integer)]) -> Either Error ())
-> [(PolicyId, [(AssetName, Integer)])] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (((AssetName, Integer) -> Either Error ())
-> [(AssetName, Integer)] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Integer -> Either Error ()
bounded (Integer -> Either Error ())
-> ((AssetName, Integer) -> Integer)
-> (AssetName, Integer)
-> Either Error ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AssetName, Integer) -> Integer
forall a b. (a, b) -> b
snd) ([(AssetName, Integer)] -> Either Error ())
-> ((PolicyId, [(AssetName, Integer)]) -> [(AssetName, Integer)])
-> (PolicyId, [(AssetName, Integer)])
-> Either Error ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PolicyId, [(AssetName, Integer)]) -> [(AssetName, Integer)]
forall a b. (a, b) -> b
snd) [(PolicyId, [(AssetName, Integer)])]
groups
  Snapshot -> Either Error Snapshot
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Integer -> [(PolicyId, [(AssetName, Integer)])] -> Snapshot
Snapshot Integer
lovelace [(PolicyId
policy, ((AssetName, Integer) -> (Int, ByteString))
-> [(AssetName, Integer)] -> [(AssetName, Integer)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (AssetName, Integer) -> (Int, ByteString)
forall {b}. (AssetName, b) -> (Int, ByteString)
nameKey [(AssetName, Integer)]
names) | (PolicyId
policy, [(AssetName, Integer)]
names) <- Map PolicyId [(AssetName, Integer)]
-> [(PolicyId, [(AssetName, Integer)])]
forall k a. Map k a -> [(k, a)]
Map.toAscList ([(PolicyId, [(AssetName, Integer)])]
-> Map PolicyId [(AssetName, Integer)]
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(PolicyId, [(AssetName, Integer)])]
groups)])
  where
    nameKey :: (AssetName, b) -> (Int, ByteString)
nameKey (AssetName
name, b
_) = let bytes :: ByteString
bytes = AssetName -> ByteString
Name.toBytes AssetName
name in (ByteString -> Int
B.length ByteString
bytes, ByteString
bytes)

-- | Signed coin quantity in lovelace, within the native signed 64-bit range.
coin :: Snapshot -> Integer
coin :: Snapshot -> Integer
coin (Snapshot Integer
result [(PolicyId, [(AssetName, Integer)])]
_) = Integer
result

-- | Stored policy/name associations in the order documented by 'mkSnapshot'.
-- The returned lists retain zero quantities, repeated names and empty groups.
assets :: Snapshot -> [(PolicyId, [(AssetName, Integer)])]
assets :: Snapshot -> [(PolicyId, [(AssetName, Integer)])]
assets (Snapshot Integer
_ [(PolicyId, [(AssetName, Integer)])]
result) = [(PolicyId, [(AssetName, Integer)])]
result

-- | Snapshot a normalized bundle, checking native signed 64-bit bounds. Input
-- normalization has already removed zero entries and combined repeated assets;
-- this operation cannot recover that discarded representation information.
fromValue :: Value.Value -> Either Error Snapshot
fromValue :: Value -> Either Error Snapshot
fromValue Value
value = Integer
-> [(PolicyId, [(AssetName, Integer)])] -> Either Error Snapshot
mkSnapshot (AssetId -> Value -> Integer
Value.quantity AssetId
Ada Value
value) (Map PolicyId [(AssetName, Integer)]
-> [(PolicyId, [(AssetName, Integer)])]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map PolicyId [(AssetName, Integer)]
groups)
  where
    groups :: Map PolicyId [(AssetName, Integer)]
groups = ([(AssetName, Integer)]
 -> [(AssetName, Integer)] -> [(AssetName, Integer)])
-> [(PolicyId, [(AssetName, Integer)])]
-> Map PolicyId [(AssetName, Integer)]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith [(AssetName, Integer)]
-> [(AssetName, Integer)] -> [(AssetName, Integer)]
forall a. Semigroup a => a -> a -> a
(<>) [(PolicyId
policy, [(AssetName
name, Integer
quantity)]) | (Native PolicyId
policy AssetName
name, Integer
quantity) <- Value -> [(AssetId, Integer)]
Value.toList Value
value]

-- | Explicitly normalize a raw snapshot into an ordinary bundle. This is lossy:
-- repeated names are added, zeros and empty groups disappear. The summed result
-- may exceed native bounds, which ordinary value encoders validate separately.
-- For any successfully snapshotted bundle, @fmap toValue (fromValue value) ==
-- Right value@. The reverse composition need not preserve a raw snapshot.
toValue :: Snapshot -> Value.Value
toValue :: Snapshot -> Value
toValue (Snapshot Integer
lovelace [(PolicyId, [(AssetName, Integer)])]
groups) = [(AssetId, Integer)] -> Value
Value.fromList ((AssetId
Ada, Integer
lovelace) (AssetId, Integer) -> [(AssetId, Integer)] -> [(AssetId, Integer)]
forall a. a -> [a] -> [a]
: [(PolicyId -> AssetName -> AssetId
Native PolicyId
policy AssetName
name, Integer
quantity) | (PolicyId
policy, [(AssetName, Integer)]
names) <- [(PolicyId, [(AssetName, Integer)])]
groups, (AssetName
name, Integer
quantity) <- [(AssetName, Integer)]
names])

bounded :: Integer -> Either Error ()
bounded :: Integer -> Either Error ()
bounded Integer
quantity = Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Integer
quantity Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
minBound :: Int64) Bool -> Bool -> Bool
&& Integer
quantity Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
maxBound :: Int64)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Integer -> Error
InvalidValueQuantity Integer
quantity))