import csv
import io
import urllib.request

URL = "https://rate.bot.com.tw/xrt/flcsv/0/day"
TARGETS = {"USD": "美元", "JPY": "日幣", "EUR": "歐元"}


def fetch_rates():
    with urllib.request.urlopen(URL, timeout=10) as resp:
        raw = resp.read().decode("utf-8-sig", errors="replace")
    reader = csv.reader(io.StringIO(raw))
    next(reader, None)
    rates = {}
    for row in reader:
        if not row:
            continue
        code = row[0].strip()
        if code in TARGETS:
            rates[code] = float(row[13])
    return rates


def main():
    rates = fetch_rates()
    print("台灣銀行 即期賣出匯率")
    print("-" * 28)
    for code, name in TARGETS.items():
        if code in rates:
            print(f"{name} ({code}): {rates[code]:.4f}")
        else:
            print(f"{name} ({code}): 查無資料")


if __name__ == "__main__":
    main()
