import urllib.request
import json
import sys

# Try to get exchange rates
url = 'https://open.er-api.com/v6/latest/USD'
try:
    with urllib.request.urlopen(url, timeout=15) as resp:
        d = json.load(resp)
    r = d['rates']
    eur_usd = 1/r['EUR']
    gbp_usd = 1/r['GBP']
    usd_jpy = r['JPY']
    usd_chf = r['CHF']
    aud_usd = 1/r['AUD']
    usd_cad = r['CAD']
    # Approximate DXY
    dxy = 0.574*eur_usd + 0.119*gbp_usd + 0.119*usd_jpy/100 + 0.091*usd_chf + 0.049*aud_usd + 0.048*usd_cad
    print(f'EUR/USD: {eur_usd:.5f}')
    print(f'GBP/USD: {gbp_usd:.5f}')
    print(f'USD/JPY: {usd_jpy:.2f}')
    print(f'USD/CHF: {usd_chf:.4f}')
    print(f'AUD/USD: {aud_usd:.5f}')
    print(f'USD/CAD: {usd_cad:.5f}')
    print(f'DXY approx: {dxy:.2f}')
    print(f'Date: {d["date"]}')
except Exception as e:
    print(f'FX_ERROR: {e}')

# Try to get gold price
url = 'https://api.gold-api.com/price/XAU'
try:
    with urllib.request.urlopen(url, timeout=15) as resp:
        d = json.load(resp)
    print(f'XAUUSD: {d["price"]:.2f}')
except Exception as e:
    print(f'GOLD_ERROR: {e}')

# Try to get calendar data
url = 'https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/usd.json'
try:
    with urllib.request.urlopen(url, timeout=15) as resp:
        d = json.load(resp)
    print(f'USD index (jsdelivr): {d.get("date", "N/A")}')
except Exception as e:
    print(f'CDN_FX_ERROR: {e}')
