#!/usr/bin/env bash

# Usage:
#   ./calc_ascii.sh "Claude"
#   ./calc_ascii.sh "Hello World" 0.1

set -euo pipefail

INPUT="${1:-Claude}"
KEY_DELAY="${2:-0.1}"

# If Calculator is already running, do nothing.
if pgrep -x "Calculator" >/dev/null 2>&1; then
  exit 0
fi

# ASCII -> HEX
HEX=$(printf "%s" "$INPUT" | xxd -p | tr -d '\n' | tr '[:lower:]' '[:upper:]')

open -a Calculator

osascript <<EOF
tell application "System Events"
    tell process "Calculator"
        repeat until (exists window 1)
            delay 0.05
        end repeat

        tell application "Finder"
            set {0, 0, screenW, screenH} to bounds of window of desktop
        end tell

        set {winW, winH} to size of window 1
        set position of window 1 to {(screenW - winW) / 2, (screenH - winH) / 2}

        delay 0.2

        -- reset display
        keystroke "c" using command down
        delay 0.1

        -- type HEX slowly
        set textToType to "$HEX"
        repeat with c in characters of textToType
            keystroke c
            delay $KEY_DELAY
        end repeat
    end tell
end tell
EOF