#!/usr/bin/env bash
# Preview by default. --create RESPONSE_FILE is an explicit real write.
set -euo pipefail
umask 077
mode=${1:---preview}
if [[ "$mode" != --preview && "$mode" != --create ]]; then
  echo 'Usage: create-watch.sh [--preview | --create RESPONSE_FILE]' >&2; exit 2
fi
body=$(python3 - <<'PY'
import json, os, re
from urllib.parse import urlsplit
address=os.environ.get('TRON_ADDRESS','')
if not re.fullmatch(r'T[1-9A-HJ-NP-Za-km-z]{33}|(?:0x)?41[0-9a-fA-F]{40}', address): raise SystemExit('Set TRON_ADDRESS to your intended TRON address')
asset=os.environ.get('ASSET','USDT'); direction=os.environ.get('DIRECTION','incoming'); target=os.environ.get('TARGET','webhook')
if asset not in ('USDT','TRX','ALL') or direction not in ('incoming','outgoing','both') or target not in ('webhook','telegram'): raise SystemExit('Invalid ASSET, DIRECTION or TARGET')
body={'address':address,'asset_filter':asset,'direction':direction}
if target=='telegram': body['telegram']=True
else:
 url=os.environ.get('WEBHOOK_URL',''); parsed=urlsplit(url)
 if parsed.scheme not in ('http','https') or not parsed.hostname or parsed.username or parsed.password or parsed.fragment: raise SystemExit('Set WEBHOOK_URL to an HTTP(S) receiver without embedded credentials or fragment')
 body['webhook_url']=url
print(json.dumps(body))
PY
)
if [[ "$mode" == --preview ]]; then
  printf '%s\n' "$body"
  echo 'Preview only. Creating enables future real notifications and uses one watch slot.' >&2
  exit 0
fi
output=${2:-}
if [[ -z "$output" || "$output" == - || -e "$output" || -L "$output" ]]; then echo 'Choose a NEW private response file; it will contain the one-time signing secret.' >&2; exit 2; fi
key=${TRONHOOKS_API_KEY:-}
if [[ ! "$key" =~ ^tw_live_[0-9a-f]{40}$ ]]; then echo 'Set TRONHOOKS_API_KEY locally to a mainnet key.' >&2; exit 2; fi
# noclobber prevents overwriting an existing response file, including symlinks.
(set -o noclobber; : > "$output")
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
printf '%s' "$body" > "$tmp"
# Pass authorization on stdin rather than exposing it in curl process arguments.
if ! printf 'header = "Authorization: Bearer %s"\n' "$key" | curl --disable --config - --fail-with-body --max-time 10 --request POST --header 'Content-Type: application/json' --data-binary "@$tmp" --output "$output" 'https://tronhooks.com/v1/watches'; then
  echo 'Request failed or outcome is uncertain. Response preserved privately. List and reconcile watches before retrying; do not assume no write occurred.' >&2
  exit 1
fi
echo 'Response saved privately. Store the one-time secret, then GET /v1/watches to verify the full configuration. No notification test was sent.'
