#!/bin/bash
#
# Rate-API — Convert Currency (Raycast Script Command)
#
# Required parameters:
# @raycast.schemaVersion 1
# @raycast.title Convert Currency
# @raycast.mode compact
#
# Optional parameters:
# @raycast.icon 💱
# @raycast.packageName Rate-API
# @raycast.argument1 { "type": "text", "placeholder": "amount" }
# @raycast.argument2 { "type": "text", "placeholder": "from (USD)", "optional": true }
# @raycast.argument3 { "type": "text", "placeholder": "to (EUR)", "optional": true }
#
# Documentation:
# @raycast.description Live currency conversion for 160+ currencies via Rate-API — no API key needed.
# @raycast.author Rate-API
# @raycast.authorURL https://rate-api.com

amount="${1:-1}"
from="$(echo "${2:-USD}" | tr '[:lower:]' '[:upper:]')"
to="$(echo "${3:-EUR}" | tr '[:lower:]' '[:upper:]')"

data="$(curl -fsS "https://rate-api.com/widget/rates?base=USD" 2>/dev/null)"
if [ -z "$data" ]; then
    echo "Could not reach rate-api.com"
    exit 1
fi

python3 - "$data" "$amount" "$from" "$to" <<'PY'
import json, sys
data = json.loads(sys.argv[1])
try:
    amt = float(sys.argv[2])
except ValueError:
    print("Amount must be a number"); sys.exit(0)
f, t = sys.argv[3], sys.argv[4]
rates = data.get("rates", {})
if f not in rates or t not in rates:
    missing = f if f not in rates else t
    print(f"Unknown currency: {missing}"); sys.exit(0)
res = amt * (rates[t] / rates[f])
print(f"{amt:g} {f} = {res:,.4f} {t}")
PY
