#!/bin/bash

# Exit on any error
set -e

# Parse command line arguments
SKIP_CONFIG=false
CONSUMER_PARTY=""
REQUEST_ID=""
ACTIVE_AT_OFFSET=""

while [[ $# -gt 0 ]]; do
  case $1 in
    --skip-config)
      SKIP_CONFIG=true
      shift
      ;;
    --consumer-party)
      CONSUMER_PARTY="$2"
      shift 2
      ;;
    --request-id)
      REQUEST_ID="$2"
      shift 2
      ;;
    --offset)
      ACTIVE_AT_OFFSET="$2"
      shift 2
      ;;
    --help|-h)
      echo "Usage: $0 [--skip-config] [OPTIONS] [--help]"
      echo ""
      echo "Read a prepaid oracle response by querying FilledRequest contracts"
      echo ""
      echo "Required Options:"
      echo "  --request-id ID                             The request ID to search for"
      echo "  --consumer-party PARTY                      The consumer party"
      echo ""
      echo "Optional Options:"
      echo "  --offset OFFSET                             Active at offset (default: latest)"
      echo "  --template-id TEMPLATE_ID                   FilledRequest template ID"
      echo "  --skip-config                               Skip loading config files"
      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 parameters
if [ -z "$REQUEST_ID" ]; then
  echo "Error: --request-id is required."
  echo "Run '$0 --help' for detailed usage information"
  exit 1
fi

if [ -z "$CONSUMER_PARTY" ]; then
  echo "Error: --consumer-party is required."
  echo "Run '$0 --help' for detailed usage information"
  exit 1
fi

echo "🔍 Reading prepaid oracle response..."
echo "Request ID: $REQUEST_ID"
echo "Consumer Party: $CONSUMER_PARTY"

# Build the request payload
if [ -n "$ACTIVE_AT_OFFSET" ]; then
  OFFSET_FIELD="\"activeAtOffset\": $ACTIVE_AT_OFFSET,"
else
  OFFSET_FIELD=""
fi

# Query for FilledRequest contracts
set +e
RESPONSE=$(curl --location "$PARTICIPANT_API_ENDPOINT/v2/state/active-contracts" \
    --fail-with-body \
    -sS \
    -H "Authorization: Bearer $CANTON_TOKEN" \
    -H "Content-Type: application/json" \
    --data-raw "$(cat <<EOF
{
    $OFFSET_FIELD
    "verbose": false,
    "eventFormat": {
        "filtersByParty": {
            "$CONSUMER_PARTY": {
                "cumulative": [
                    {
                        "identifierFilter": {
                            "TemplateFilter": {
                                "value": {
                                    "includeCreatedEventBlob": false,
                                    "templateId": "$FILLED_REQUEST_TEMPLATE_ID"
                                }
                            }
                        }
                    }
                ]
            }
        },
        "verbose": false
    }
}
EOF
)")
CURL_EXIT_CODE=$?

# Check if request succeeded
if [ $CURL_EXIT_CODE -ne 0 ]; then
    echo "❌ Failed to query active contracts"
    echo "$RESPONSE"
    exit 1
fi

# Extract the createArgument for the matching requestId
RESULT=$(echo "$RESPONSE" | jq -r --arg reqId "$REQUEST_ID" '
  .[] | 
  select(.contractEntry.JsActiveContract.createdEvent.createArgument.requestId == $reqId) | 
  .contractEntry.JsActiveContract.createdEvent.createArgument
')

if [ -z "$RESULT" ] || [ "$RESULT" = "null" ]; then
    echo "❌ No FilledRequest found with requestId: $REQUEST_ID"
    exit 1
fi

echo ""
echo "✅ Found FilledRequest for requestId: $REQUEST_ID"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "$RESULT"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
