#!/usr/bin/env python3
# unitconv - convert units (length, weight, temperature, data) with a table
# Usage: unitconv VALUE FROM [TO] [--list] [--category CAT]
#   With only FROM, prints a conversion table to every unit in that category.
#   Example: unitconv 5 km mi | unitconv 2 kg | unitconv --list length
import argparse, sys

# base units: m, kg, K, byte, litre
TABLES = {
    "length": {"mm": 0.001, "cm": 0.01, "m": 1.0, "km": 1000.0,
               "in": 0.0254, "ft": 0.3048, "yd": 0.9144, "mi": 1609.344,
               "nmi": 1852.0, "ly": 9.4607304725808e15},
    "weight": {"mg": 1e-6, "g": 0.001, "kg": 1.0, "t": 1000.0,
               "oz": 0.028349523125, "lb": 0.45359237, "st": 6.35029318},
    "temperature": {},  # handled specially (offsets)
    "data": {"bit": 0.125, "B": 1.0, "KB": 1e3, "MB": 1e6, "GB": 1e9, "TB": 1e12,
             "KiB": 1024.0, "MiB": 1024.0**2, "GiB": 1024.0**3, "TiB": 1024.0**4},
    "volume": {"ml": 0.001, "l": 1.0, "m3": 1000.0, "tsp": 0.00492892159375,
               "tbsp": 0.01478676478125, "floz": 0.0295735295625,
               "cup": 0.2365882365, "pt": 0.473176473, "qt": 0.946352946,
               "gal": 3.785411784, "gal-uk": 4.54609},
    "speed": {"m/s": 1.0, "km/h": 1 / 3.6, "mph": 0.44704, "knot": 0.514444, "ft/s": 0.3048},
}
ALIASES = {"meter": "m", "meters": "m", "kilometer": "km", "kilometers": "km",
           "mile": "mi", "miles": "mi", "foot": "ft", "feet": "ft", "inch": "in",
           "inches": "in", "pound": "lb", "pounds": "lb", "ounce": "oz",
           "gram": "g", "grams": "g", "byte": "B", "bytes": "B", "liter": "l",
           "liters": "l", "litre": "l", "celsius": "C", "fahrenheit": "F",
           "kelvin": "K", "c": "C", "f": "F", "k": "K"}

def norm(u):
    u = u.strip()
    return ALIASES.get(u.lower(), ALIASES.get(u, u))

def to_kelvin(v, u):
    return {"C": v + 273.15, "F": (v - 32) * 5 / 9 + 273.15, "K": v}[u]

def from_kelvin(k, u):
    return {"C": k - 273.15, "F": (k - 273.15) * 9 / 5 + 32, "K": k}[u]

def find_cat(u):
    if u in ("C", "F", "K"):
        return "temperature"
    for cat, t in TABLES.items():
        if u in t:
            return cat
    return None

def selftest():
    assert abs(norm("miles") and TABLES["length"]["mi"] * 1 - 1609.344) < 1e-9
    assert abs(5 * 1000 / 1609.344 - 3.106855) < 1e-6  # 5 km in miles
    assert abs(to_kelvin(0, "C") - 273.15) < 1e-9
    assert abs(from_kelvin(273.15, "F") - 32) < 1e-9
    assert abs(2 * TABLES["weight"]["kg"] / TABLES["weight"]["lb"] - 4.409245) < 1e-6
    print("unitconv selftest: ok (length, weight, temperature conversions)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="unitconv",
        description="Convert units (length, weight, temperature, data, volume, speed).")
    p.add_argument("value", nargs="?", type=float, help="value to convert")
    p.add_argument("from_unit", nargs="?", help="unit to convert from")
    p.add_argument("to_unit", nargs="?", help="unit to convert to (omit for a full table)")
    p.add_argument("--list", metavar="CAT", nargs="?", const="all",
                   help="list units (optionally for one category)")
    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.list is not None:
        cats = [a.list] if a.list != "all" else sorted(TABLES) + ["temperature"]
        for cat in cats:
            units = ["C", "F", "K"] if cat == "temperature" else sorted(TABLES.get(cat, {}))
            if not units:
                print(f"unitconv: unknown category {cat!r}", file=sys.stderr); return 2
            print(f"{cat}: {' '.join(units)}")
        return 0
    if a.value is None or not a.from_unit:
        p.error("VALUE and FROM are required (or use --list)")
    fu, tu = norm(a.from_unit), norm(a.to_unit) if a.to_unit else None
    cat = find_cat(fu)
    if cat is None:
        print(f"unitconv: unknown unit {a.from_unit!r}", file=sys.stderr); return 2
    if cat == "temperature":
        k = to_kelvin(a.value, fu)
        if tu:
            if tu not in ("C", "F", "K"):
                print(f"unitconv: {tu!r} is not a temperature unit", file=sys.stderr); return 2
            print(f"{a.value:g} {fu} = {from_kelvin(k, tu):g} {tu}")
        else:
            for u in ("C", "F", "K"):
                print(f"  {u}: {from_kelvin(k, u):g}")
        return 0
    if tu:
        if tu not in TABLES[cat]:
            print(f"unitconv: {tu!r} is not a {cat} unit", file=sys.stderr); return 2
        print(f"{a.value:g} {fu} = {a.value * TABLES[cat][fu] / TABLES[cat][tu]:g} {tu}")
    else:
        for u in TABLES[cat]:
            print(f"  {u}: {a.value * TABLES[cat][fu] / TABLES[cat][u]:g}")
    return 0

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