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

-- | Pure queries of the current builder draft for deferred redeemers. Compose
-- required indices, inspect selected inputs, then supply an explicit script-data
-- encoder to 'redeemer'. Queries run again whenever the builder invokes the
-- callback; positions are specific to that draft, not the final signed body.
--
-- @
-- import qualified Cometa.PlutusData as Data
-- import qualified Cometa.Transaction.Deferred as Deferred
--
-- spendingRedeemer reference =
--   Deferred.redeemer (Data.Integer . toInteger) (Deferred.inputIndex reference)
-- @
module Cometa.Transaction.Deferred
  ( Query,
    draft,
    selectedInputs,
    fromEither,
    run,
    inputIndex,
    referenceInputIndex,
    mintPolicyIndex,
    withdrawalIndex,
    voteIndex,
    proposalIndex,
    redeemerIndex,
    outputIndex,
    outputIndexWhere,
    redeemer,
    encodedRedeemer,
  )
where

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

import Cometa.Address.Reward (RewardAddress)
import Cometa.Error (Error (InvalidBuildingRequest))
import Cometa.Evaluation (RedeemerId)
import Cometa.Governance.Proposal (Proposal)
import Cometa.Governance.Voting (Voter)
import qualified Cometa.PlutusData as Data
import Cometa.PolicyId (PolicyId)
import Cometa.Transaction (Transaction)
import qualified Cometa.Transaction as Tx
import qualified Cometa.Transaction.Body as Body
import qualified Cometa.Transaction.Fields as Fields
import qualified Cometa.Transaction.Indices as Indices
import Cometa.Transaction.Input (Input)
import Cometa.Transaction.Output (Output)
import Cometa.Transaction.Plan (DeferredRedeemer)
import Cometa.Transaction.Utxo (Utxo)
import Data.Text (Text)
import Data.Word (Word64)

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

-- | A read-only draft query with explicit expected failure. 'Functor',
-- 'Applicative' and 'Monad' share the same immutable draft and selected-input
-- snapshot throughout a run and stop at the first 'Left'. No native or network
-- effects occur. The constructor is hidden; use the queries and 'fromEither'.
newtype Query a = Query (Transaction -> [Utxo] -> Either Error a)

instance Functor Query where
  fmap :: forall a b. (a -> b) -> Query a -> Query b
fmap a -> b
f (Query Transaction -> [Utxo] -> Either Error a
query) = (Transaction -> [Utxo] -> Either Error b) -> Query b
forall a. (Transaction -> [Utxo] -> Either Error a) -> Query a
Query (\Transaction
transaction [Utxo]
inputs -> (a -> b) -> Either Error a -> Either Error b
forall a b. (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> b
f (Transaction -> [Utxo] -> Either Error a
query Transaction
transaction [Utxo]
inputs))

instance Applicative Query where
  pure :: forall a. a -> Query a
pure a
value = (Transaction -> [Utxo] -> Either Error a) -> Query a
forall a. (Transaction -> [Utxo] -> Either Error a) -> Query a
Query (\Transaction
_ [Utxo]
_ -> a -> Either Error a
forall a b. b -> Either a b
Right a
value)
  Query Transaction -> [Utxo] -> Either Error (a -> b)
function <*> :: forall a b. Query (a -> b) -> Query a -> Query b
<*> Query Transaction -> [Utxo] -> Either Error a
argument = (Transaction -> [Utxo] -> Either Error b) -> Query b
forall a. (Transaction -> [Utxo] -> Either Error a) -> Query a
Query ((Transaction -> [Utxo] -> Either Error b) -> Query b)
-> (Transaction -> [Utxo] -> Either Error b) -> Query b
forall a b. (a -> b) -> a -> b
$ \Transaction
transaction [Utxo]
inputs ->
    Transaction -> [Utxo] -> Either Error (a -> b)
function Transaction
transaction [Utxo]
inputs Either Error (a -> b) -> Either Error a -> Either Error b
forall a b.
Either Error (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Transaction -> [Utxo] -> Either Error a
argument Transaction
transaction [Utxo]
inputs

instance Monad Query where
  Query Transaction -> [Utxo] -> Either Error a
query >>= :: forall a b. Query a -> (a -> Query b) -> Query b
>>= a -> Query b
next = (Transaction -> [Utxo] -> Either Error b) -> Query b
forall a. (Transaction -> [Utxo] -> Either Error a) -> Query a
Query ((Transaction -> [Utxo] -> Either Error b) -> Query b)
-> (Transaction -> [Utxo] -> Either Error b) -> Query b
forall a b. (a -> b) -> a -> b
$ \Transaction
transaction [Utxo]
inputs -> do
    a
value <- Transaction -> [Utxo] -> Either Error a
query Transaction
transaction [Utxo]
inputs
    Query b -> Transaction -> [Utxo] -> Either Error b
forall a. Query a -> Transaction -> [Utxo] -> Either Error a
run (a -> Query b
next a
value) Transaction
transaction [Utxo]
inputs

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

-- | The current callback draft. Inspect it with the ordinary pure transaction
-- observers. Subsequent balancing may change its body and indices.
draft :: Query Transaction
draft :: Query Transaction
draft = (Transaction -> [Utxo] -> Either Error Transaction)
-> Query Transaction
forall a. (Transaction -> [Utxo] -> Either Error a) -> Query a
Query (\Transaction
transaction [Utxo]
_ -> Transaction -> Either Error Transaction
forall a b. b -> Either a b
Right Transaction
transaction)

-- | The exact selected-input list supplied to this callback, retaining order.
-- This is not a network query and need not include reference inputs. 'run' does
-- not validate or reorder an independently supplied snapshot.
selectedInputs :: Query [Utxo]
selectedInputs :: Query [Utxo]
selectedInputs = (Transaction -> [Utxo] -> Either Error [Utxo]) -> Query [Utxo]
forall a. (Transaction -> [Utxo] -> Either Error a) -> Query a
Query (\Transaction
_ [Utxo]
inputs -> [Utxo] -> Either Error [Utxo]
forall a b. b -> Either a b
Right [Utxo]
inputs)

-- | Lift existing pure validation. A 'Left' stops subsequent query steps.
fromEither :: Either Error a -> Query a
fromEither :: forall a. Either Error a -> Query a
fromEither Either Error a
result = (Transaction -> [Utxo] -> Either Error a) -> Query a
forall a. (Transaction -> [Utxo] -> Either Error a) -> Query a
Query (\Transaction
_ [Utxo]
_ -> Either Error a
result)

-- | Evaluate against one draft and selected-input snapshot. Useful for testing
-- a query before installing it in a plan. Inputs remain unchanged.
run :: Query a -> Transaction -> [Utxo] -> Either Error a
run :: forall a. Query a -> Transaction -> [Utxo] -> Either Error a
run (Query Transaction -> [Utxo] -> Either Error a
query) = Transaction -> [Utxo] -> Either Error a
query

-- | Required spending-input position in hash-byte then numeric-index order.
-- Duplicates use their first position. Absence returns 'InvalidBuildingRequest'.
inputIndex :: Input -> Query Word64
inputIndex :: Input -> Query Word64
inputIndex Input
reference = Text -> (Transaction -> Maybe Word64) -> Query Word64
required Text
"Deferred spending input is missing" (Input -> Transaction -> Maybe Word64
Indices.findInput Input
reference)

-- | Required reference-input position in the same order as 'inputIndex'.
-- Absence returns 'InvalidBuildingRequest'.
referenceInputIndex :: Input -> Query Word64
referenceInputIndex :: Input -> Query Word64
referenceInputIndex Input
reference = Text -> (Transaction -> Maybe Word64) -> Query Word64
required Text
"Deferred reference input is missing" (Input -> Transaction -> Maybe Word64
Indices.findReferenceInput Input
reference)

-- | Required mint-policy position in ascending policy-hash order. Empty and
-- zero-quantity imported policies count. Absence returns 'InvalidBuildingRequest'.
mintPolicyIndex :: PolicyId -> Query Word64
mintPolicyIndex :: PolicyId -> Query Word64
mintPolicyIndex PolicyId
policy = Text -> (Transaction -> Maybe Word64) -> Query Word64
required Text
"Deferred mint policy is missing" (PolicyId -> Transaction -> Maybe Word64
Indices.findMintPolicy PolicyId
policy)

-- | Required withdrawal position in ledger reward-account order, as documented
-- by 'Indices.findWithdrawal'. Absence returns 'InvalidBuildingRequest'.
withdrawalIndex :: RewardAddress -> Query Word64
withdrawalIndex :: RewardAddress -> Query Word64
withdrawalIndex RewardAddress
account = Text -> (Transaction -> Maybe Word64) -> Query Word64
required Text
"Deferred withdrawal is missing" (RewardAddress -> Transaction -> Maybe Word64
Indices.findWithdrawal RewardAddress
account)

-- | Required voter position in ledger role and credential order, independent
-- of the number of action votes. Absence returns 'InvalidBuildingRequest'.
voteIndex :: Voter -> Query Word64
voteIndex :: Voter -> Query Word64
voteIndex Voter
voter = Text -> (Transaction -> Maybe Word64) -> Query Word64
required Text
"Deferred voter is missing" (Voter -> Transaction -> Maybe Word64
Indices.findVote Voter
voter)

-- | Required proposal position in insertion order, comparing canonical
-- encodings and using the first duplicate. Absence returns 'InvalidBuildingRequest'.
proposalIndex :: Proposal -> Query Word64
proposalIndex :: Proposal -> Query Word64
proposalIndex Proposal
proposal = Text -> (Transaction -> Maybe Word64) -> Query Word64
required Text
"Deferred proposal is missing" (Proposal -> Transaction -> Maybe Word64
Indices.findProposal Proposal
proposal)

-- | Required rank among redeemers ordered by purpose and purpose index. This
-- is not the authorized body-item index. Absence returns 'InvalidBuildingRequest'.
redeemerIndex :: RedeemerId -> Query Word64
redeemerIndex :: RedeemerId -> Query Word64
redeemerIndex RedeemerId
identifier = Text -> (Transaction -> Maybe Word64) -> Query Word64
required Text
"Deferred redeemer is missing" (RedeemerId -> Transaction -> Maybe Word64
Indices.findRedeemer RedeemerId
identifier)

required :: Text -> (Transaction -> Maybe Word64) -> Query Word64
required :: Text -> (Transaction -> Maybe Word64) -> Query Word64
required Text
message Transaction -> Maybe Word64
lookupIndex = do
  Transaction
transaction <- Query Transaction
draft
  Either Error Word64 -> Query Word64
forall a. Either Error a -> Query a
fromEither (Either Error Word64
-> (Word64 -> Either Error Word64)
-> Maybe Word64
-> Either Error Word64
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error Word64
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
message)) Word64 -> Either Error Word64
forall a b. b -> Either a b
Right (Transaction -> Maybe Word64
lookupIndex Transaction
transaction))

-- | Unique output with equal semantic fields, including exact inline datum
-- bytes. Creation order determines the index. Missing or multiple equal outputs
-- return 'InvalidBuildingRequest'; no first-match choice is made.
outputIndex :: Output -> Query Word64
outputIndex :: Output -> Query Word64
outputIndex Output
output = (Output -> Bool) -> Query Word64
outputIndexWhere (Output -> Output -> Bool
forall a. Eq a => a -> a -> Bool
== Output
output)

-- | Unique output satisfying a pure predicate, in creation order. No match or
-- multiple matches return distinct 'InvalidBuildingRequest' diagnostics.
outputIndexWhere :: (Output -> Bool) -> Query Word64
outputIndexWhere :: (Output -> Bool) -> Query Word64
outputIndexWhere Output -> Bool
matches = do
  Transaction
transaction <- Query Transaction
draft
  let outputs :: [Output]
outputs = Fields -> [Output]
Fields.fieldOutputs (Body -> Fields
Body.bodyFields (EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)))
      positions :: [Word64]
positions = [Word64
index | (Word64
index, Output
output) <- [Word64] -> [Output] -> [(Word64, Output)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Word64
0 ..] [Output]
outputs, Output -> Bool
matches Output
output]
  Either Error Word64 -> Query Word64
forall a. Either Error a -> Query a
fromEither (Either Error Word64 -> Query Word64)
-> Either Error Word64 -> Query Word64
forall a b. (a -> b) -> a -> b
$ case [Word64]
positions of
    [] -> Error -> Either Error Word64
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Deferred output is missing")
    [Word64
index] -> Word64 -> Either Error Word64
forall a b. b -> Either a b
Right Word64
index
    [Word64]
_ -> Error -> Either Error Word64
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Deferred output is ambiguous")

-- | Turn a query into the existing plan callback using an explicit application
-- data encoder. Encoding uses 'Data.fromData'; the query's first failure is
-- propagated unchanged. Repeated callbacks rerun the query against each draft.
redeemer :: (a -> Data.PlutusData) -> Query a -> DeferredRedeemer
redeemer :: forall a. (a -> PlutusData) -> Query a -> DeferredRedeemer
redeemer a -> PlutusData
encode Query a
query = Query EncodedPlutusData -> DeferredRedeemer
encodedRedeemer (PlutusData -> EncodedPlutusData
Data.fromData (PlutusData -> EncodedPlutusData)
-> (a -> PlutusData) -> a -> EncodedPlutusData
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> PlutusData
encode (a -> EncodedPlutusData) -> Query a -> Query EncodedPlutusData
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Query a
query)

-- | Turn exact validated script data into the existing plan callback without
-- re-encoding its CBOR. Compatible with top-level and subtransaction plan
-- callbacks; both receive the builder's 'Transaction' draft. Pure index queries
-- inspect the supplied draft's top-level body and do not descend into nested
-- subtransactions. Use a raw callback for other contextual policies.
encodedRedeemer :: Query Data.EncodedPlutusData -> DeferredRedeemer
encodedRedeemer :: Query EncodedPlutusData -> DeferredRedeemer
encodedRedeemer = Query EncodedPlutusData -> DeferredRedeemer
forall a. Query a -> Transaction -> [Utxo] -> Either Error a
run