-- 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 #-}

-- | Identify a governance proposal by its containing transaction and index.
-- These are standalone protocol identities; construction does not establish
-- that a proposal exists or is currently eligible for voting.
--
-- @
-- import qualified Cometa.Governance.ActionId as ActionId
-- import qualified Cometa.TransactionId as TransactionId
--
-- firstProposal :: TransactionId.TransactionId -> ActionId.ActionId
-- firstProposal transaction = ActionId.ActionId transaction 0
-- @
module Cometa.Governance.ActionId
  ( ActionId (..),
    encodeCbor,
    decodeCbor,
    toText,
    fromText,
  )
where

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

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

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

-- | Fresh definite CBOR @[transaction hash bytes, unsigned index]@ with the
-- shortest integer encoding. The index retains the full unsigned 64-bit range.
encodeCbor :: ActionId -> ByteString
encodeCbor :: ActionId -> ByteString
encodeCbor = ActionId -> ByteString
Internal.encodeActionId

-- | Decode exactly one complete action identifier. Both definite and indefinite
-- arrays and nonminimal integer encodings are accepted. Wrong arity, hash length,
-- non-unsigned index or trailing bytes returns
-- 'Cometa.Error.InvalidGovernanceCbor'. The result is semantic data; this
-- function does not retain the original encoding.
decodeCbor :: ByteString -> Either Error ActionId
decodeCbor :: ByteString -> Either Error ActionId
decodeCbor = ByteString -> Either Error ActionId
Internal.decodeActionId

-- | Encode the CIP-129 @gov_action@ Bech32 identifier: 32 transaction hash
-- bytes followed by the one-byte proposal index. Indices above 255 return
-- 'InvalidGovernanceActionTextIndex' without truncation. CBOR retains the full
-- unsigned 64-bit index range independently of this narrower display format.
toText :: ActionId -> Either Error Text
toText :: ActionId -> Either Error Text
toText (ActionId TransactionId
transaction Word64
actionIndex)
  | Word64
actionIndex Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> Word64
255 = Error -> Either Error Text
forall a b. a -> Either a b
Left (Word64 -> Error
InvalidGovernanceActionTextIndex Word64
actionIndex)
  | Bool
otherwise = 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 governance action prefix"))) HumanReadablePart -> Either Error HumanReadablePart
forall a b. b -> Either a b
Right (Text -> Either HumanReadablePartError HumanReadablePart
Bech32.humanReadablePartFromText Text
"gov_action")
      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 (TransactionId -> ByteString
TransactionId.toBytes TransactionId
transaction ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> Word8 -> ByteString
B.singleton (Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
actionIndex))))

-- | Decode a checksummed CIP-129 @gov_action@ identifier with exactly 33
-- payload bytes. Uniform upper or lower case is accepted; mixed case, other
-- prefixes, incorrect padding, checksum or length returns
-- 'InvalidGovernanceActionText'. The decoded index is always 0 through 255.
fromText :: Text -> Either Error ActionId
fromText :: Text -> Either Error ActionId
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)
  Bool -> Either Error ()
unlessValid (HumanReadablePart -> Text
Bech32.humanReadablePartToText HumanReadablePart
prefix Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"gov_action")
  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)
  Bool -> Either Error ()
unlessValid (ByteString -> Int
B.length ByteString
payload Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
33)
  TransactionId
transaction <- ByteString -> Either Error TransactionId
TransactionId.fromBytes (Int -> ByteString -> ByteString
B.take Int
32 ByteString
payload)
  case ByteString -> Maybe (Word8, ByteString)
B.uncons (Int -> ByteString -> ByteString
B.drop Int
32 ByteString
payload) of
    Just (Word8
actionIndex, ByteString
_) -> ActionId -> Either Error ActionId
forall a b. b -> Either a b
Right (TransactionId -> Word64 -> ActionId
ActionId TransactionId
transaction (Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
actionIndex))
    Maybe (Word8, ByteString)
Nothing -> Either Error ActionId
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
InvalidGovernanceActionText Text
"Expected a CIP-129 gov_action identifier with a 33-byte payload")
    unlessValid :: Bool -> Either Error ()
unlessValid Bool
True = () -> Either Error ()
forall a b. b -> Either a b
Right ()
    unlessValid Bool
False = Either Error ()
forall a. Either Error a
failure