#!/bin/bash

# Exit on any error
set -e

# Parse command line arguments
SKIP_CONFIG=false
CONSUMER_PARTY=""
ORACLE_PARTY=""
DSO_PARTY=""
LOCKED_AMOUNT=""
CATALOG=""
PROVIDER_CLIENT_ID=""
PROVIDER_CLIENT_SECRET=""
REQUEST_FACTORY_CID=""
AMULET_RULES_CID=""
OPEN_MINING_ROUND_CID=""
CONSUMER_AMULET_CID=""
DATA_REQUEST='{\"@type\":\"DataRequest\",\"name\":\"oracletest20\",\"description\":\"Sample data request for testing\",\"universe\":{\"@type\":\"Universe\",\"contains\":[{\"@type\":\"Identifier\",\"identifierType\":\"TICKER\",\"identifierValue\":\"FRTR 3.5 11/25/2035 144A Govt\"}]},\"fieldList\":{\"@type\":\"DataFieldList\",\"contains\":[{\"mnemonic\":\"PX_LAST\"}]},\"trigger\":{\"@type\":\"SubmitTrigger\"},\"formatting\":{\"@type\":\"MediaType\",\"outputMediaType\":\"application/json\"}}'
AMULET_RULES_BLOB="CgMyLjESsQ4KRQByTANpCmiCwr8LrSQX1kqO3J5Cp0oWA9OOMCRqP4xeTMoSEiBgKLTZYcurXm9bLY0L833SIWO2+CpysSC+TWqFfjR9iBINc3BsaWNlLWFtdWxldBpkCkA2N2ZhYzJmODUzYmNlOGRiZjBiOTgxN2JiNWJhN2M1OWYxMGU4MTIwYjdjODA4Njk2ZjcwMTBlNWYwYzhhNzkxEgZTcGxpY2USC0FtdWxldFJ1bGVzGgtBbXVsZXRSdWxlcyLyC2rvCwpNCks6SURTTzo6MTIyMGJlNThjMjllNjVkZTQwYmYyNzNiZTFkYzJiMjY2ZDQzYTlhMDAyZWE1YjE4OTU1YWVlZjdhYWM4ODFiYjQ3MWEKlwsKlAtqkQsKiAsKhQtqggsKkgEKjwFqjAEKFgoUahIKEAoOMgwwLjAwMDAwMDAwMDAKFgoUahIKEAoOMgwwLjAwMDAxOTAyNTkKHAoaahgKEAoOMgwwLjAwMDAwMDAwMDAKBAoCWgAKFgoUahIKEAoOMgwwLjAwMD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NWJhN2M1OWYxMGU4MTIwYjdjODA4Njk2ZjcwMTBlNWYwYzhhNzkxEgZTcGxpY2USBVJvdW5kGg9PcGVuTWluaW5nUm91bmQi3ANq2QMKTQpLOklEU086OjEyMjBiZTU4YzI5ZTY1ZGU0MGJmMjczYmUxZGMyYjI2NmQ0M2E5YTAwMmVhNWIxODk1NWFlZWY3YWFjODgxYmI0NzFhCgwKCmoICgYKBBiC0AMKEAoOMgwwLjE3MzYxNTAwMDAKCwoJKTiy6XaXSQYACgsKCSk4PnC+l0kGAAoQCg5qDAoKCggYgJja95ONCAqSAQqPAWqMAQoWChRqEgoQCg4yDDAuMDAwMDAwMDAwMAoWChRqEgoQCg4yDDAuMDAwMDE5MDI1OQocChpqGAoQCg4yDDAuMDAwMDAwMDAwMAoECgJaAAoWChRqEgoQCg4yDDAuMDAwMDAwMDAwMAoQCg4yDDEuMDAwMDAwMDAwMAoFCgMYyAEKBQoDGMgBCgQKAhhkCpYBCpMBapABChoKGDIWMjAwMDAwMDAwMDAuMDAwMDAwMDAwMAoQCg4yDDAuMTIwMDAwMDAwMAoQCg4yDDAuNDAwMDAwMDAwMAoQCg4yDDAuMjAwMDAwMDAwMAoUChIyEDIwMDAwLjAwMDAwMDAwMDAKEAoOMgwwLjYwMDAwMDAwMDAKFAoSUhAKDjIMMy4zMzAwMDAwMDAwCg4KDGoKCggKBhiAmJq8BCpJRFNPOjoxMjIwYmU1OGMyOWU2NWRlNDBiZjI3M2JlMWRjMmIyNjZkNDNhOWEwMDJlYTViMTg5NTVhZWVmN2FhYzg4MWJiNDcxYTk4bCZTl0kGAEIqCiYKJAgBEiCInqipk4VRQddwxraxDp/+i0hq2ML3zPGnT2HLD8EuVBAe"

while [[ $# -gt 0 ]]; do
  case $1 in
    --skip-config)
      SKIP_CONFIG=true
      shift
      ;;
    --consumer-party)
      CONSUMER_PARTY="$2"
      shift 2
      ;;
    --oracle-party)
      ORACLE_PARTY="$2"
      shift 2
      ;;
    --dso-party)
      DSO_PARTY="$2"
      shift 2
      ;;
    --locked-amount)
      LOCKED_AMOUNT="$2"
      shift 2
      ;;
    --catalog)
      CATALOG="$2"
      shift 2
      ;;
    --provider-client-id)
      PROVIDER_CLIENT_ID="$2"
      shift 2
      ;;
    --provider-client-secret)
      PROVIDER_CLIENT_SECRET="$2"
      shift 2
      ;;
    --factory-cid)
      REQUEST_FACTORY_CID="$2"
      shift 2
      ;;
    --rules-cid)
      AMULET_RULES_CID="$2"
      shift 2
      ;;
    --mining-round-cid)
      OPEN_MINING_ROUND_CID="$2"
      shift 2
      ;;
    --amulet-cid)
      CONSUMER_AMULET_CID="$2"
      shift 2
      ;;
    --help|-h)
      echo "Usage: $0 [--skip-config] [OPTIONS] [--help]"
      echo ""
      echo "Create a prepaid oracle request by exercising RequestFactory CreateRequest choice"
      echo ""
      echo "Required Options:"
      echo "  --factory-cid CID                           RequestFactory contract ID"
      echo "  --rules-cid CID                             AmuletRules contract ID"
      echo "  --mining-round-cid CID                      OpenMiningRound contract ID"
      echo "  --amulet-cid CID                            Consumer's Amulet contract ID"
      echo "  --consumer-party PARTY                      The consumer party (default: Consumer::...)"
      echo "  --oracle-party PARTY                        The oracle party (default: Oracle::...)"
      echo "  --dso-party PARTY                           The DSO party (default: DSO::...)"
      echo "  --catalog ID                                Catalog ID"
      echo "  --locked-amount AMOUNT                      Locked amount in Amulet (default: 10.0)"
      echo "  --provider-client-id ID                              Client ID for oracle access (default: demo-client-id-123)"
      echo "  --provider-client-secret SECRET                      Client secret for oracle access (default: demo-client-secret-123)"
      echo "  --help, -h                                  Show this help message"
      exit 0
      ;;
    *)
      echo "Unknown option $1"
      echo "Usage: $0 [--skip-config] [OPTIONS] [--help]"
      echo "Run '$0 --help' for detailed usage information"
      exit 1
      ;;
  esac
done

# Load configuration files unless skipped
if [ "$SKIP_CONFIG" = false ]; then
  # Check if config files exist
  if [ -f "./.env" ]; then
    source ./.env
  fi
  if [ -f "./set_env.sh" ]; then
    source ./set_env.sh
  fi
fi

# Check if required variables are set
if [ -z "$PARTICIPANT_API_ENDPOINT" ] || [ -z "$CANTON_TOKEN" ]; then
  echo "Error: Required environment variables not set. Set PARTICIPANT_API_ENDPOINT and CANTON_TOKEN."
  exit 1
fi

# Validate required contract IDs
if [ -z "$REQUEST_FACTORY_CID" ] || [ -z "$AMULET_RULES_CID" ] || [ -z "$OPEN_MINING_ROUND_CID" ] || [ -z "$CONSUMER_AMULET_CID" ]; then
  echo "Error: Required contract IDs not provided."
  echo "Please provide: --factory-cid, --rules-cid, --mining-round-cid, --amulet-cid"
  echo "Run '$0 --help' for detailed usage information"
  exit 1
fi

echo "🚀 Creating prepaid oracle request..."
echo "Consumer Party: $CONSUMER_PARTY"
echo "Oracle Party: $ORACLE_PARTY"
echo "Locked Amount: $LOCKED_AMOUNT"
echo "Data Request: $DATA_REQUEST"
echo "Client ID: $PROVIDER_CLIENT_ID"

# Generate unique command ID
COMMAND_ID="create-request-cmd-$(date +%s)-$(shuf -i 1000-9999 -n 1)"

# Execute CreateRequest choice
echo "📋 Exercising CreateRequest choice..."

echo "data request: $DATA_REQUEST"

set +e
REQUEST_RESPONSE=$(curl -X POST $PARTICIPANT_API_ENDPOINT/v2/commands/submit-and-wait-for-transaction-tree \
    --fail-with-body \
    -sS \
    -H "Authorization: Bearer $CANTON_TOKEN" \
    -H "Content-Type: application/json" \
    --data-raw  "$(cat <<EOF
        {
          "actAs": [
            "$CONSUMER_PARTY"
          ],
          "commandId": "$COMMAND_ID",
          "commands": [
            {
              "actAs": [
                "$CONSUMER_PARTY"
              ],
              "commandId": "$COMMAND_ID",
              "ExerciseCommand": {
                "templateId": "$REQUEST_FACTORY_TEMPLATE_ID",
                "contractId": "$REQUEST_FACTORY_CID",
                "choice": "CreateRequest",
                "choiceArgument": {
                  "dso": "$DSO_PARTY",
                  "amuletRulesCid": "$AMULET_RULES_CID",
                  "openRoundCid": "$OPEN_MINING_ROUND_CID",
                  "inputs": [
                    {
                      "tag": "InputAmulet",
                      "value": "$CONSUMER_AMULET_CID"
                    }
                  ],
                  "catalog": "$CATALOG",
                  "dataRequest": "$DATA_REQUEST",
                  "clientId": "$PROVIDER_CLIENT_ID",
                  "clientSecret": "$PROVIDER_CLIENT_SECRET",
                  "lockedAmount": "$LOCKED_AMOUNT"
                }
              }
            }
          ],
          "disclosedContracts": [
              {
                  "templateId": "$AMULET_RULES_TEMPLATE_ID",
                  "contractId": "$AMULET_RULES_CID",
                  "synchronizerId": "$GLOBAL_DOMAIN",
                  "createdEventBlob": "$AMULET_RULES_BLOB"
              },
              {
                  "templateId": "$OPEN_MINING_ROUND_TEMPLATE_ID",
                  "contractId": "$OPEN_MINING_ROUND_CID",
                  "synchronizerId": "$GLOBAL_DOMAIN",
                  "createdEventBlob": "$OPEN_MINING_ROUND_BLOB"
              }
          ]
        }
EOF
)")
CURL_EXIT_CODE=$?

# Check if request creation succeeded
if [ $CURL_EXIT_CODE -ne 0 ]; then
    echo "❌ Failed to create request"
    echo "$REQUEST_RESPONSE"
    exit 1
fi


# Extract requestId from the response (robust to non-numeric event keys)
REQUEST_ID=$(echo "$REQUEST_RESPONSE" | jq -r '
  .transactionTree.eventsById | to_entries[] |
  select(.value.ExercisedTreeEvent.value.choice == "CreateRequest") |
  .value.ExercisedTreeEvent.value.exerciseResult.requestId // empty
')

echo ""
echo "🎉 Prepaid oracle request created successfully!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🆔 Request ID: $REQUEST_ID"
echo "📋 Request Contract ID: ${REQUEST_CONTRACT_ID:-"(check output above)"}"
echo "🔒 Locked Amulet Contract ID: ${LOCKED_AMULET_CONTRACT_ID:-"(check output above)"}"
echo "👤 Consumer Party: $CONSUMER_PARTY"
echo "🔮 Oracle Party: $ORACLE_PARTY"
echo "💰 Payment Amount: $PAYMENT_AMOUNT Amulet"
echo "📊 Data Request: $DATA_REQUEST"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
