#!/usr/bin/env bash
# Hello ticket: start a session, send one message, poll for the reply, end the session.
# Needs curl and jq. Run: WETEL_API_KEY=sk_... WETEL_AGENT_ID=7 bash hello-ticket.sh
set -euo pipefail
API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
AGENT_ID="${WETEL_AGENT_ID:-1}"
CLIENT_ID="ticket-$(date +%s)" # one clientId per conversation
TEXT="My laptop cannot connect to the office VPN since this morning."

read -r -d '' START <<'GRAPHQL' || true
mutation StartSession($input: SdkStartInput!) {
  sdkStart(input: $input) {
    sessionId
    avatarToken
    agentId
    graphqlEndpoint
  }
}
GRAPHQL
read -r -d '' SEND <<'GRAPHQL' || true
mutation SendMessage($input: SdkSendMessageInput!) {
  sdkSendMessage(input: $input)
}
GRAPHQL
read -r -d '' POLL <<'GRAPHQL' || true
query PollSession($externalCustomerId: String!, $first: Int) {
  sessionsByExternalCustomerId(externalCustomerId: $externalCustomerId, first: $first) {
    totalCount
    edges {
      node {
        id
        status
        messages {
          id
          role
          text
          turnIndex
          createdAt
        }
      }
    }
  }
}
GRAPHQL
read -r -d '' END <<'GRAPHQL' || true
mutation EndSession($input: SdkEndSessionInput!) {
  sdkEndSession(input: $input) {
    sessionId
    durationSeconds
    evaluation {
      score
      summary
    }
  }
}
GRAPHQL

# gql QUERY VARIABLES_JSON AUTH_HEADER: prints .data, or the first error and exits.
gql() {
  local response
  response=$(jq -n --arg query "$1" --argjson variables "$2" '{query: $query, variables: $variables}' |
    curl -sS "$API_URL" -H "Content-Type: application/json" -H "x-huat-platform: customer" -H "$3" --data-binary @-)
  if [ "$(jq '.errors | length' <<<"$response")" != "0" ]; then
    jq -r '.errors[0] | "\(.extensions.code): \(.message)"' <<<"$response" >&2
    exit 1
  fi
  jq '.data' <<<"$response"
}

# 1. Start a session with the API key.
STARTED=$(gql "$START" "$(jq -n --argjson agentId "$AGENT_ID" --arg clientId "$CLIENT_ID" '{input: {agentId: $agentId, clientId: $clientId}}')" "X-Api-Key: $WETEL_API_KEY")
SESSION_ID=$(jq '.sdkStart.sessionId' <<<"$STARTED")
AVATAR_TOKEN=$(jq -r '.sdkStart.avatarToken' <<<"$STARTED")

# 2. Send the message with the session token. It returns true at once.
gql "$SEND" "$(jq -n --argjson sessionId "$SESSION_ID" --arg text "$TEXT" '{input: {sessionId: $sessionId, text: $text}}')" "Authorization: Bearer $AVATAR_TOKEN" >/dev/null

# 3. Poll the session's messages until the reply arrives
#    (the reply is every MODEL message after the last USER message).
REPLY=""
DEADLINE=$(($(date +%s) + 60))
while [ -z "$REPLY" ] && [ "$(date +%s)" -lt "$DEADLINE" ]; do
  sleep 2
  POLLED=$(gql "$POLL" "$(jq -n --arg clientId "$CLIENT_ID" '{externalCustomerId: $clientId, first: 1}')" "X-Api-Key: $WETEL_API_KEY")
  REPLY=$(jq -r --argjson id "$SESSION_ID" '
    .sessionsByExternalCustomerId.edges[].node | select(.id == $id) | .messages
    | ((map(.role) | rindex("USER")) // -1) as $u
    | .[($u + 1):] | map(select(.role == "MODEL") | .text) | join("\n")' <<<"$POLLED")
done
echo "${REPLY:-No reply within the timeout.}"

# 4. End the session with the session token.
gql "$END" "$(jq -n --argjson sessionId "$SESSION_ID" '{input: {sessionId: $sessionId}}')" "Authorization: Bearer $AVATAR_TOKEN" >/dev/null
