#!/bin/bash

# This script calculates the estimated token count for a given set of tools
# and a sample message using the Anthropic API's /v1/messages/count_tokens endpoint.
# It reads tool definitions from a JSON file generated by the `cmd/token-count` Go program.
#
# Requires:
#   - curl : For making HTTP requests to the Anthropic API.
#   - jq   : For constructing the JSON payload from the input file.
#
# Usage:
#   ./token.sh -k <YOUR_ANTHROPIC_API_KEY> -i <path/to/your/tools.json>
#
# Mandatory Arguments:
#   -k, --api-key      : Your Anthropic API key.
#   -i, --input-json   : Path to the JSON file containing the tool definitions.
#                        This file should be an array of tool objects, each having
#                        `name`, `description`, and `input_schema` fields.
#
# Example:
#   # Assuming tools.json is in the current directory
#   ./token.sh -k sk-ant-xxxxxxxx -i tools.json
#
# Output:
#   The script outputs the JSON response from the Anthropic API,
#   which typically includes the calculated token count.

# Default values
API_KEY=""
INPUT_JSON=""

# Parse command-line arguments
TEMP=$(getopt -o k:i: --long api-key:,input-json: -n 'token.sh' -- "$@")
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP`: they are essential!
eval set -- "$TEMP"

while true; do
  case "$1" in
    -k | --api-key ) API_KEY="$2"; shift 2 ;;
    -i | --input-json ) INPUT_JSON="$2"; shift 2 ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

# Validate mandatory arguments
if [ -z "$API_KEY" ]; then
    echo "Error: API Key is mandatory. Use -k or --api-key." >&2
    exit 1
fi

if [ -z "$INPUT_JSON" ]; then
    echo "Error: Input JSON file path is mandatory. Use -i or --input-json." >&2
    exit 1
fi

if [ ! -f "$INPUT_JSON" ]; then
    echo "Error: Input JSON file not found: $INPUT_JSON" >&2
    exit 1
fi

# Read tools definition from the input JSON file
TOOLS_JSON=$(cat "$INPUT_JSON")

# Construct the JSON payload using jq
# Note: We keep the example message structure for now.
# We pass the tools JSON as a string argument to jq and use --argjson to parse it.
JSON_PAYLOAD=$(jq -n --argjson tools "$TOOLS_JSON" '{
  model: "claude-3-7-sonnet-20250219",
  tools: $tools,
  messages: [
    {
      role: "user",
      content: "Show me a list of Portainer environments."
    }
  ]
}')

# Check if jq succeeded
if [ $? != 0 ]; then
    echo "Error: Failed to construct JSON payload with jq. Is the input JSON valid?" >&2
    exit 1
fi


# Make the API call
curl https://api.anthropic.com/v1/messages/count_tokens \
    --header "x-api-key: $API_KEY" \
    --header "content-type: application/json" \
    --header "anthropic-version: 2023-06-01" \
    --data "$JSON_PAYLOAD"

echo # Add a newline for cleaner output
