-- 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.
{-# LANGUAGE OverloadedStrings #-}

-- | Delegation targets distinguish a DRep credential from the predefined
-- always-abstain and always-no-confidence targets. Special targets cannot be
-- used as voting authorities.
--
-- @
-- import qualified Cometa.Governance.DRep as DRep
--
-- abstainingTarget :: DRep.DRep
-- abstainingTarget = DRep.AlwaysAbstain
-- @
module Cometa.Governance.DRep
  ( DRep (..),
    encodeCbor,
    decodeCbor,
    toText,
    fromText,
  )
where

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

import qualified Codec.Binary.Bech32 as Bech32
import qualified Cometa.Credential as Credential
import Cometa.Error (Error (..))
import Cometa.Internal.Governance (DRep (..))
import qualified Cometa.Internal.Governance as Internal
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Text (Text)

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

-- | Encode fresh definite CBOR: @[0, key hash]@, @[1, script hash]@, @[2]@
-- (always abstain), or @[3]@ (always no confidence).
encodeCbor :: DRep -> ByteString
encodeCbor :: DRep -> ByteString
encodeCbor = DRep -> ByteString
Internal.encodeDRep

-- | Decode one complete DRep. Definite or indefinite arrays and nonminimal
-- unsigned codes are accepted. Codes, arity and 28-byte credential lengths are
-- checked; invalid input or trailing bytes returns
-- 'Cometa.Error.InvalidGovernanceCbor'. Original encoding is not retained.
decodeCbor :: ByteString -> Either Error DRep
decodeCbor :: ByteString -> Either Error DRep
decodeCbor = ByteString -> Either Error DRep
Internal.decodeDRep

-- | Encode a credential DRep as CIP-129 @drep@ Bech32 text, using header
-- @0x22@ for a key or @0x23@ for a script and its 28-byte hash. The special
-- abstain and no-confidence delegation targets have no credential identifier;
-- they return 'UnsupportedOperation'.
toText :: DRep -> Either Error Text
toText :: DRep -> Either Error Text
toText (DRepCredential Credential DRep
credential) = do
  HumanReadablePart
prefix <- (HumanReadablePartError -> Either Error HumanReadablePart)
-> (HumanReadablePart -> Either Error HumanReadablePart)
-> Either HumanReadablePartError HumanReadablePart
-> Either Error HumanReadablePart
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Either Error HumanReadablePart
-> HumanReadablePartError -> Either Error HumanReadablePart
forall a b. a -> b -> a
const (Error -> Either Error HumanReadablePart
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"Invalid built-in DRep prefix"))) HumanReadablePart -> Either Error HumanReadablePart
forall a b. b -> Either a b
Right (Text -> Either HumanReadablePartError HumanReadablePart
Bech32.humanReadablePartFromText Text
"drep")
  let payload :: ByteString
payload = case Credential DRep
credential of
        Credential.KeyCredential KeyHash DRep
hash -> Word8 -> ByteString -> ByteString
B.cons Word8
0x22 (KeyHash DRep -> ByteString
forall purpose. KeyHash purpose -> ByteString
Credential.keyHashBytes KeyHash DRep
hash)
        Credential.ScriptCredential ScriptHash
hash -> Word8 -> ByteString -> ByteString
B.cons Word8
0x23 (ScriptHash -> ByteString
Credential.scriptHashBytes ScriptHash
hash)
  Text -> Either Error Text
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (HumanReadablePart -> DataPart -> Text
Bech32.encodeLenient HumanReadablePart
prefix (ByteString -> DataPart
Bech32.dataPartFromBytes ByteString
payload))
toText DRep
AlwaysAbstain = Error -> Either Error Text
forall a b. a -> Either a b
Left (Text -> Error
UnsupportedOperation Text
"DRep.toText: always-abstain has no credential identifier")
toText DRep
AlwaysNoConfidence = Error -> Either Error Text
forall a b. a -> Either a b
Left (Text -> Error
UnsupportedOperation Text
"DRep.toText: always-no-confidence has no credential identifier")

-- | Import either CIP-105 (28-byte @drep@ key or @drep_script@ script) or
-- CIP-129 (29-byte @drep@ header and hash) text. Uniform upper or lower case is
-- accepted. Mixed case, invalid checksum/padding, other prefixes or headers and
-- wrong lengths return 'InvalidDRepText'. Re-encoding always produces CIP-129.
fromText :: Text -> Either Error DRep
fromText :: Text -> Either Error DRep
fromText Text
text = do
  (HumanReadablePart
prefix, DataPart
part) <- (DecodingError -> Either Error (HumanReadablePart, DataPart))
-> ((HumanReadablePart, DataPart)
    -> Either Error (HumanReadablePart, DataPart))
-> Either DecodingError (HumanReadablePart, DataPart)
-> Either Error (HumanReadablePart, DataPart)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Either Error (HumanReadablePart, DataPart)
-> DecodingError -> Either Error (HumanReadablePart, DataPart)
forall a b. a -> b -> a
const Either Error (HumanReadablePart, DataPart)
forall a. Either Error a
failure) (HumanReadablePart, DataPart)
-> Either Error (HumanReadablePart, DataPart)
forall a b. b -> Either a b
Right (Text -> Either DecodingError (HumanReadablePart, DataPart)
Bech32.decodeLenient Text
text)
  ByteString
payload <- Either Error ByteString
-> (ByteString -> Either Error ByteString)
-> Maybe ByteString
-> Either Error ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Either Error ByteString
forall a. Either Error a
failure ByteString -> Either Error ByteString
forall a b. b -> Either a b
Right (DataPart -> Maybe ByteString
Bech32.dataPartToBytes DataPart
part)
  case (HumanReadablePart -> Text
Bech32.humanReadablePartToText HumanReadablePart
prefix, ByteString -> Int
B.length ByteString
payload) of
    (Text
"drep", Int
28) -> ByteString -> Either Error DRep
key ByteString
payload
    (Text
"drep_script", Int
28) -> ByteString -> Either Error DRep
script ByteString
payload
    (Text
"drep", Int
29) -> case ByteString -> Maybe (Word8, ByteString)
B.uncons ByteString
payload of
      Just (Word8
0x22, ByteString
hash) -> ByteString -> Either Error DRep
key ByteString
hash
      Just (Word8
0x23, ByteString
hash) -> ByteString -> Either Error DRep
script ByteString
hash
      Maybe (Word8, ByteString)
_ -> Either Error DRep
forall a. Either Error a
failure
    (Text, Int)
_ -> Either Error DRep
forall a. Either Error a
failure
  where
    failure :: Either Error a
    failure :: forall a. Either Error a
failure = Error -> Either Error a
forall a b. a -> Either a b
Left (Text -> Error
InvalidDRepText Text
"Expected a CIP-105 or CIP-129 DRep credential identifier")
    key :: ByteString -> Either Error DRep
key ByteString
payload = Credential DRep -> DRep
DRepCredential (Credential DRep -> DRep)
-> (KeyHash DRep -> Credential DRep) -> KeyHash DRep -> DRep
forall b c a. (b -> c) -> (a -> b) -> a -> c
. KeyHash DRep -> Credential DRep
forall purpose. KeyHash purpose -> Credential purpose
Credential.KeyCredential (KeyHash DRep -> DRep)
-> Either Error (KeyHash DRep) -> Either Error DRep
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error (KeyHash DRep)
forall purpose. ByteString -> Either Error (KeyHash purpose)
Credential.keyHashFromBytes ByteString
payload
    script :: ByteString -> Either Error DRep
script ByteString
payload = Credential DRep -> DRep
DRepCredential (Credential DRep -> DRep)
-> (ScriptHash -> Credential DRep) -> ScriptHash -> DRep
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ScriptHash -> Credential DRep
forall purpose. ScriptHash -> Credential purpose
Credential.ScriptCredential (ScriptHash -> DRep)
-> Either Error ScriptHash -> Either Error DRep
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Either Error ScriptHash
Credential.scriptHashFromBytes ByteString
payload