#!/usr/bin/env python3
# currconv - currency converter with an editable offline rate file
# Usage: currconv AMOUNT FROM [TO] [--rates FILE] [--set-rate CUR RATE] [--list]
#   Rates are units of currency per 1 USD, stored in JSON (default
#   ~/.config/fileutils/rates.json). With no TO, converts to every known currency.
#   Example: currconv 100 USD EUR | currconv 50 EUR --list
import argparse, json, os, sys

DEFAULT_RATES = os.path.expanduser("~/.config/fileutils/rates.json")
# units per 1 USD (approximate, Dec 2026 — edit the file to update)
BUILTIN = {"USD": 1.0, "EUR": 0.92, "GBP": 0.79, "JPY": 155.0, "CHF": 0.88,
           "CAD": 1.40, "AUD": 1.52, "NZD": 1.68, "CNY": 7.25, "INR": 84.5,
           "KRW": 1380.0, "BRL": 5.90, "MXN": 20.5, "SEK": 10.6, "NOK": 11.0,
           "DKK": 6.85, "PLN": 4.10, "CZK": 23.2, "HUF": 365.0, "TRY": 34.5,
           "ZAR": 18.2, "SGD": 1.35, "HKD": 7.80, "TWD": 32.5, "THB": 34.0,
           "IDR": 15800.0, "PHP": 58.0, "ILS": 3.65, "AED": 3.67, "SAR": 3.75}

def load_rates(path):
    rates = dict(BUILTIN)
    if os.path.exists(path):
        try:
            rates.update(json.load(open(path)))
        except (OSError, ValueError) as e:
            print(f"currconv: warning: ignoring bad rates file: {e}", file=sys.stderr)
    return rates

def convert(amount, frm, to, rates):
    return amount / rates[frm] * rates[to]

def selftest():
    r = dict(BUILTIN)
    assert abs(convert(100, "USD", "EUR", r) - 92) < 1e-9
    assert abs(convert(92, "EUR", "USD", r) - 100) < 1e-9
    assert abs(convert(convert(50, "USD", "JPY", r), "JPY", "GBP", r)
               - convert(50, "USD", "GBP", r)) < 1e-6
    print("currconv selftest: ok (USD->EUR, round-trip, cross-rate consistency)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="currconv",
        description="Currency converter with an editable offline rate file.")
    p.add_argument("amount", nargs="?", type=float, help="amount to convert")
    p.add_argument("from_cur", nargs="?", help="currency code, e.g. USD")
    p.add_argument("to_cur", nargs="?", help="target currency (omit for all currencies)")
    p.add_argument("--rates", default=DEFAULT_RATES, help="JSON rates file")
    p.add_argument("--set-rate", nargs=2, metavar=("CUR", "RATE"),
                   help="set RATE (per 1 USD) for CUR in the rates file and exit")
    p.add_argument("--list", action="store_true", help="list known currencies and rates")
    p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if a.set_rate:
        cur, rate = a.set_rate[0].upper(), float(a.set_rate[1])
        if rate <= 0:
            print("currconv: rate must be > 0", file=sys.stderr); return 2
        rates = load_rates(a.rates)
        rates[cur] = rate
        os.makedirs(os.path.dirname(a.rates), exist_ok=True)
        json.dump(rates, open(a.rates, "w"), indent=2, sort_keys=True)
        print(f"rate set: 1 USD = {rate:g} {cur} (saved to {a.rates})")
        return 0
    rates = load_rates(a.rates)
    if a.list:
        for cur in sorted(rates):
            print(f"  {cur}: {rates[cur]:g} per USD")
        return 0
    if a.amount is None or not a.from_cur:
        p.error("AMOUNT and FROM currency are required (or use --list)")
    frm = a.from_cur.upper()
    if frm not in rates:
        print(f"currconv: unknown currency {frm!r} (try --list)", file=sys.stderr); return 2
    if a.to_cur:
        to = a.to_cur.upper()
        if to not in rates:
            print(f"currconv: unknown currency {to!r}", file=sys.stderr); return 2
        print(f"{a.amount:g} {frm} = {convert(a.amount, frm, to, rates):.2f} {to}")
    else:
        for to in sorted(rates):
            if to != frm:
                print(f"  {to}: {convert(a.amount, frm, to, rates):.2f}")
    return 0

if __name__ == "__main__":
    sys.exit(main())
