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

-- | Named cardano-c status codes, including success. Unknown numeric codes are
-- preserved exactly for logging and interchange. A code can be named even when
-- this package does not expose operations from the corresponding domain.
--
-- @
-- import qualified Cometa.Error.Code as Code
--
-- main :: IO ()
-- main = print (Code.fromNumber (Code.toNumber Code.InvalidArgument) == Code.InvalidArgument)
-- @
module Cometa.Error.Code
  ( -- * Status codes
    ErrorCode
      ( Success,
        GenericFailure,
        InsufficientBufferSize,
        NullPointer,
        MemoryAllocationFailed,
        OutOfBoundsMemoryRead,
        OutOfBoundsMemoryWrite,
        InvalidArgument,
        InvalidUrl,
        ElementNotFound,
        EncodingFailure,
        DecodingFailure,
        ChecksumMismatch,
        InvalidJson,
        IntegerOverflow,
        IntegerUnderflow,
        ConversionFailed,
        IndexOutOfBounds,
        InvalidCertificateType,
        NotImplemented,
        InvalidPassphrase,
        IllegalState,
        DuplicateKey,
        JsonTypeMismatch,
        LossOfPrecision,
        InvalidMagic,
        InvalidChecksum,
        InvalidBlake2bHashSize,
        InvalidEd25519SignatureSize,
        InvalidEd25519PublicKeySize,
        InvalidEd25519PrivateKeySize,
        InvalidBip32PublicKeySize,
        InvalidBip32PrivateKeySize,
        InvalidBip32DerivationIndex,
        UnexpectedCborType,
        InvalidCborValue,
        InvalidCborArraySize,
        InvalidCborMapSize,
        DuplicateCborMapKey,
        InvalidCborMapKey,
        InvalidAddressType,
        InvalidAddressFormat,
        InvalidCredentialType,
        InvalidPlutusDataConversion,
        InvalidDatumType,
        InvalidScriptLanguage,
        InvalidNativeScriptType,
        InvalidPlutusCostModel,
        InvalidProposalProcedureType,
        InvalidMetadatumConversion,
        InvalidMetadatumTextStringSize,
        InvalidMetadatumBoundedBytesSize,
        InvalidHttpRequest,
        InsufficientBalance,
        UtxoNotFragmentedEnough,
        UtxoFullyDepleted,
        MaximumInputCountExceeded,
        UnbalancedSubTransactions,
        DisallowedSupplementalDatums,
        MissingRedeemer,
        ScriptEvaluationFailure
      ),

    -- * Numeric conversion
    fromNumber,
    toNumber,

    -- * Inspection
    isKnown,
    knownCodes,
  )
where

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

-- | A native status code. 'Success' represents a successful operation; all other
-- named constructors represent failures. Use 'fromNumber' to construct a code
-- from any integer, and 'isKnown' to distinguish named and unrecognized codes.
-- Equality distinguishes exact numeric codes. 'Show' is diagnostic only.
data ErrorCode
  = -- | Successful operation.
    Success
  | -- | Generic error.
    GenericFailure
  | -- | Insufficient buffer size.
    InsufficientBufferSize
  | -- | Operation over a null pointer.
    NullPointer
  | -- | Memory could not be allocated.
    MemoryAllocationFailed
  | -- | Out of bounds memory read.
    OutOfBoundsMemoryRead
  | -- | Out of bounds memory write.
    OutOfBoundsMemoryWrite
  | -- | Invalid argument.
    InvalidArgument
  | -- | Invalid URL.
    InvalidUrl
  | -- | Element not found.
    ElementNotFound
  | -- | Encoding failure.
    EncodingFailure
  | -- | Decoding failure.
    DecodingFailure
  | -- | Invalid checksum.
    ChecksumMismatch
  | -- | Invalid JSON.
    InvalidJson
  | -- | An integer exceeds its upper bound.
    IntegerOverflow
  | -- | An integer is below its lower bound.
    IntegerUnderflow
  | -- | Conversion error.
    ConversionFailed
  | -- | Index out of bounds.
    IndexOutOfBounds
  | -- | Invalid certificate type.
    InvalidCertificateType
  | -- | The operation is not implemented.
    NotImplemented
  | -- | The passphrase is invalid.
    InvalidPassphrase
  | -- | The state of the object is illegal.
    IllegalState
  | -- | The element is already present.
    DuplicateKey
  | -- | The JSON type is unexpected.
    JsonTypeMismatch
  | -- | The serialization or deserialization process resulted in a loss of precision.
    LossOfPrecision
  | -- | The magic number is invalid.
    InvalidMagic
  | -- | The checksum is invalid.
    InvalidChecksum
  | -- | The hash size is invalid.
    InvalidBlake2bHashSize
  | -- | The Ed25519 signature size is invalid.
    InvalidEd25519SignatureSize
  | -- | The Ed25519 public key size is invalid.
    InvalidEd25519PublicKeySize
  | -- | The Ed25519 private key size is invalid.
    InvalidEd25519PrivateKeySize
  | -- | The BIP32 public key size is invalid.
    InvalidBip32PublicKeySize
  | -- | The BIP32 private key size is invalid.
    InvalidBip32PrivateKeySize
  | -- | The BIP32 derivation index is invalid.
    InvalidBip32DerivationIndex
  | -- | The CBOR type is unexpected.
    UnexpectedCborType
  | -- | The CBOR type is expected, but its value is invalid or out of range.
    InvalidCborValue
  | -- | The CBOR array size is invalid.
    InvalidCborArraySize
  | -- | The CBOR map size is invalid.
    InvalidCborMapSize
  | -- | The CBOR map key is duplicated.
    DuplicateCborMapKey
  | -- | The CBOR map key is invalid.
    InvalidCborMapKey
  | -- | The address type is invalid.
    InvalidAddressType
  | -- | The address format is invalid.
    InvalidAddressFormat
  | -- | The credential type is invalid.
    InvalidCredentialType
  | -- | The Plutus data conversion is invalid.
    InvalidPlutusDataConversion
  | -- | The Plutus datum type is invalid.
    InvalidDatumType
  | -- | The script language is invalid.
    InvalidScriptLanguage
  | -- | The native script type is invalid.
    InvalidNativeScriptType
  | -- | The Plutus cost model is invalid.
    InvalidPlutusCostModel
  | -- | The governance action type is invalid.
    InvalidProposalProcedureType
  | -- | The metadatum conversion is invalid.
    InvalidMetadatumConversion
  | -- | The metadatum text string size is invalid.
    InvalidMetadatumTextStringSize
  | -- | The metadatum bounded byte string size is invalid.
    InvalidMetadatumBoundedBytesSize
  | -- | The HTTP request is invalid.
    InvalidHttpRequest
  | -- | Available UTxO value is less than the requested output value.
    InsufficientBalance
  | -- | The selection algorithm requires more UTxO entries to cover the outputs.
    UtxoNotFragmentedEnough
  | -- | Selection exhausted the available UTxO entries before covering all outputs.
    UtxoFullyDepleted
  | -- | Progress would exceed the selection algorithm's maximum input count.
    MaximumInputCountExceeded
  | -- | Subtransactions do not conserve value as required by the batch.
    UnbalancedSubTransactions
  | -- | The top-level transaction carries a witness datum disallowed for its batch.
    DisallowedSupplementalDatums
  | -- | A Plutus script purpose in the transaction or its subtransactions lacks a redeemer.
    MissingRedeemer
  | -- | The transaction script evaluation failed.
    ScriptEvaluationFailure
  | UnknownCode !Integer
  deriving (ErrorCode -> ErrorCode -> Bool
(ErrorCode -> ErrorCode -> Bool)
-> (ErrorCode -> ErrorCode -> Bool) -> Eq ErrorCode
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ErrorCode -> ErrorCode -> Bool
== :: ErrorCode -> ErrorCode -> Bool
$c/= :: ErrorCode -> ErrorCode -> Bool
/= :: ErrorCode -> ErrorCode -> Bool
Eq, Int -> ErrorCode -> ShowS
[ErrorCode] -> ShowS
ErrorCode -> String
(Int -> ErrorCode -> ShowS)
-> (ErrorCode -> String)
-> ([ErrorCode] -> ShowS)
-> Show ErrorCode
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ErrorCode -> ShowS
showsPrec :: Int -> ErrorCode -> ShowS
$cshow :: ErrorCode -> String
show :: ErrorCode -> String
$cshowList :: [ErrorCode] -> ShowS
showList :: [ErrorCode] -> ShowS
Show)

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

-- | Interpret a numeric status code. Every integer is accepted, including
-- negative values and values outside machine integer ranges, without truncation.
-- A recognized number becomes its named constructor; all others remain unknown.
--
-- @toNumber (fromNumber number) == number@
fromNumber :: Integer -> ErrorCode
fromNumber :: Integer -> ErrorCode
fromNumber Integer
number = case Integer -> [(Integer, ErrorCode)] -> Maybe ErrorCode
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Integer
number [(ErrorCode -> Integer
toNumber ErrorCode
code, ErrorCode
code) | ErrorCode
code <- [ErrorCode]
knownCodes] of
  Just ErrorCode
code -> ErrorCode
code
  Maybe ErrorCode
Nothing -> Integer -> ErrorCode
UnknownCode Integer
number

-- | Return the exact numeric code. No conversion to a bounded machine integer
-- occurs. This is the inverse of 'fromNumber' on all 'ErrorCode' values.
toNumber :: ErrorCode -> Integer
toNumber :: ErrorCode -> Integer
toNumber ErrorCode
code = case ErrorCode
code of
  ErrorCode
Success -> Integer
0
  ErrorCode
GenericFailure -> Integer
1
  ErrorCode
InsufficientBufferSize -> Integer
2
  ErrorCode
NullPointer -> Integer
3
  ErrorCode
MemoryAllocationFailed -> Integer
4
  ErrorCode
OutOfBoundsMemoryRead -> Integer
5
  ErrorCode
OutOfBoundsMemoryWrite -> Integer
6
  ErrorCode
InvalidArgument -> Integer
7
  ErrorCode
InvalidUrl -> Integer
8
  ErrorCode
ElementNotFound -> Integer
9
  ErrorCode
EncodingFailure -> Integer
10
  ErrorCode
DecodingFailure -> Integer
11
  ErrorCode
ChecksumMismatch -> Integer
12
  ErrorCode
InvalidJson -> Integer
13
  ErrorCode
IntegerOverflow -> Integer
14
  ErrorCode
IntegerUnderflow -> Integer
15
  ErrorCode
ConversionFailed -> Integer
16
  ErrorCode
IndexOutOfBounds -> Integer
17
  ErrorCode
InvalidCertificateType -> Integer
18
  ErrorCode
NotImplemented -> Integer
19
  ErrorCode
InvalidPassphrase -> Integer
20
  ErrorCode
IllegalState -> Integer
21
  ErrorCode
DuplicateKey -> Integer
22
  ErrorCode
JsonTypeMismatch -> Integer
23
  ErrorCode
LossOfPrecision -> Integer
100
  ErrorCode
InvalidMagic -> Integer
101
  ErrorCode
InvalidChecksum -> Integer
102
  ErrorCode
InvalidBlake2bHashSize -> Integer
200
  ErrorCode
InvalidEd25519SignatureSize -> Integer
201
  ErrorCode
InvalidEd25519PublicKeySize -> Integer
202
  ErrorCode
InvalidEd25519PrivateKeySize -> Integer
203
  ErrorCode
InvalidBip32PublicKeySize -> Integer
204
  ErrorCode
InvalidBip32PrivateKeySize -> Integer
205
  ErrorCode
InvalidBip32DerivationIndex -> Integer
206
  ErrorCode
UnexpectedCborType -> Integer
300
  ErrorCode
InvalidCborValue -> Integer
301
  ErrorCode
InvalidCborArraySize -> Integer
302
  ErrorCode
InvalidCborMapSize -> Integer
303
  ErrorCode
DuplicateCborMapKey -> Integer
304
  ErrorCode
InvalidCborMapKey -> Integer
305
  ErrorCode
InvalidAddressType -> Integer
400
  ErrorCode
InvalidAddressFormat -> Integer
401
  ErrorCode
InvalidCredentialType -> Integer
500
  ErrorCode
InvalidPlutusDataConversion -> Integer
600
  ErrorCode
InvalidDatumType -> Integer
601
  ErrorCode
InvalidScriptLanguage -> Integer
700
  ErrorCode
InvalidNativeScriptType -> Integer
701
  ErrorCode
InvalidPlutusCostModel -> Integer
702
  ErrorCode
InvalidProposalProcedureType -> Integer
800
  ErrorCode
InvalidMetadatumConversion -> Integer
900
  ErrorCode
InvalidMetadatumTextStringSize -> Integer
901
  ErrorCode
InvalidMetadatumBoundedBytesSize -> Integer
902
  ErrorCode
InvalidHttpRequest -> Integer
1000
  ErrorCode
InsufficientBalance -> Integer
1100
  ErrorCode
UtxoNotFragmentedEnough -> Integer
1101
  ErrorCode
UtxoFullyDepleted -> Integer
1102
  ErrorCode
MaximumInputCountExceeded -> Integer
1103
  ErrorCode
UnbalancedSubTransactions -> Integer
1104
  ErrorCode
DisallowedSupplementalDatums -> Integer
1105
  ErrorCode
MissingRedeemer -> Integer
1106
  ErrorCode
ScriptEvaluationFailure -> Integer
1200
  UnknownCode Integer
number -> Integer
number

-- | Whether a code has a name in this build of the package.
-- This does not indicate success: use equality with 'Success' for that purpose.
isKnown :: ErrorCode -> Bool
isKnown :: ErrorCode -> Bool
isKnown (UnknownCode Integer
_) = Bool
False
isKnown ErrorCode
_ = Bool
True

-- | Every named code, including 'Success', once each, in numeric order.
-- Unknown numeric codes are excluded. Values have gaps; do not infer a code
-- by adding to or subtracting from another code.
knownCodes :: [ErrorCode]
knownCodes :: [ErrorCode]
knownCodes =
  [ ErrorCode
Success,
    ErrorCode
GenericFailure,
    ErrorCode
InsufficientBufferSize,
    ErrorCode
NullPointer,
    ErrorCode
MemoryAllocationFailed,
    ErrorCode
OutOfBoundsMemoryRead,
    ErrorCode
OutOfBoundsMemoryWrite,
    ErrorCode
InvalidArgument,
    ErrorCode
InvalidUrl,
    ErrorCode
ElementNotFound,
    ErrorCode
EncodingFailure,
    ErrorCode
DecodingFailure,
    ErrorCode
ChecksumMismatch,
    ErrorCode
InvalidJson,
    ErrorCode
IntegerOverflow,
    ErrorCode
IntegerUnderflow,
    ErrorCode
ConversionFailed,
    ErrorCode
IndexOutOfBounds,
    ErrorCode
InvalidCertificateType,
    ErrorCode
NotImplemented,
    ErrorCode
InvalidPassphrase,
    ErrorCode
IllegalState,
    ErrorCode
DuplicateKey,
    ErrorCode
JsonTypeMismatch,
    ErrorCode
LossOfPrecision,
    ErrorCode
InvalidMagic,
    ErrorCode
InvalidChecksum,
    ErrorCode
InvalidBlake2bHashSize,
    ErrorCode
InvalidEd25519SignatureSize,
    ErrorCode
InvalidEd25519PublicKeySize,
    ErrorCode
InvalidEd25519PrivateKeySize,
    ErrorCode
InvalidBip32PublicKeySize,
    ErrorCode
InvalidBip32PrivateKeySize,
    ErrorCode
InvalidBip32DerivationIndex,
    ErrorCode
UnexpectedCborType,
    ErrorCode
InvalidCborValue,
    ErrorCode
InvalidCborArraySize,
    ErrorCode
InvalidCborMapSize,
    ErrorCode
DuplicateCborMapKey,
    ErrorCode
InvalidCborMapKey,
    ErrorCode
InvalidAddressType,
    ErrorCode
InvalidAddressFormat,
    ErrorCode
InvalidCredentialType,
    ErrorCode
InvalidPlutusDataConversion,
    ErrorCode
InvalidDatumType,
    ErrorCode
InvalidScriptLanguage,
    ErrorCode
InvalidNativeScriptType,
    ErrorCode
InvalidPlutusCostModel,
    ErrorCode
InvalidProposalProcedureType,
    ErrorCode
InvalidMetadatumConversion,
    ErrorCode
InvalidMetadatumTextStringSize,
    ErrorCode
InvalidMetadatumBoundedBytesSize,
    ErrorCode
InvalidHttpRequest,
    ErrorCode
InsufficientBalance,
    ErrorCode
UtxoNotFragmentedEnough,
    ErrorCode
UtxoFullyDepleted,
    ErrorCode
MaximumInputCountExceeded,
    ErrorCode
UnbalancedSubTransactions,
    ErrorCode
DisallowedSupplementalDatums,
    ErrorCode
MissingRedeemer,
    ErrorCode
ScriptEvaluationFailure
  ]