#!/usr/bin/env python3
import subprocess
import sys
from decimal import Decimal, ROUND_DOWN, InvalidOperation

DECIMALS = 9  # TR1T has 9 decimal places
MASTER_BIG_TR1T = "0x1d5f6ba29f33c0651f365ab963ec1b4189a5125d88c8f6b6405c682f48f2c93d"
TR1T_TYPE = "0xf4d403ce2cb2d0a0b05af6945167acd933644c6c835dff577ae14e52edbf5bfd::tungsten::TUNGSTEN"

def to_nanos(tr1t_str: str) -> int:
    try:
        amt = Decimal(tr1t_str)
    except InvalidOperation:
        raise SystemExit("Invalid amount. Example: 1, 0.5, 2.75")
    if amt <= 0:
        raise SystemExit("Amount must be > 0.")
    nanos = (amt * (Decimal(10) ** DECIMALS)).quantize(Decimal(1), rounding=ROUND_DOWN)
    return int(nanos)

def send_tr1t(to_address: str, tr1t_amount: str):
    if not (to_address.startswith("0x") and len(to_address) >= 3):
        raise SystemExit("Invalid address. Must start with 0x...")
    nanos = to_nanos(tr1t_amount)

    cmd = f"""
    new_id=$(iota client split-coin \
      --coin-id {MASTER_BIG_TR1T} \
      --amounts {nanos} \
      --gas-budget 5000000 \
      --json | jq -r '.objectChanges[] | select(.type=="created" and .objectType=="0x2::coin::Coin<{TR1T_TYPE}>") | .objectId' | head -n1) \
    && iota client transfer --to {to_address} --object-id "$new_id" --gas-budget 5000000 --json
    """
    res = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if res.returncode != 0:
        print(res.stderr.strip())
        sys.exit(res.returncode)
    print(res.stdout.strip())

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: send_tr1t.py <to_address> <amount_in_TR1T>")
        print("Example: send_tr1t.py 0xabc... 1.5   # sends 1.5 TR1T")
        sys.exit(1)
    send_tr1t(sys.argv[1], sys.argv[2])
