#!/usr/bin/env python3
# tempconv - temperature converter (C/F/K) with a conversion table
# Usage: tempconv VALUE [FROM] [--to TO]
#   FROM defaults to C. With no --to, prints a table in C, F, K and Rankine.
#   Example: tempconv 100 C | tempconv 32 F --to C | tempconv 0 --to K
import argparse, sys

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

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

UNITS = {"c": "C", "celsius": "C", "f": "F", "fahrenheit": "F",
         "k": "K", "kelvin": "K", "r": "R", "rankine": "R"}

def selftest():
    assert abs(to_k(0, "C") - 273.15) < 1e-9
    assert abs(from_k(273.15, "F") - 32) < 1e-9
    assert abs(from_k(to_k(100, "C"), "F") - 212) < 1e-9
    assert abs(from_k(to_k(-40, "C"), "F") + 40) < 1e-9  # -40 is the same in C and F
    assert abs(to_k(0, "K")) < 1e-9 and abs(from_k(0, "R")) < 1e-9
    print("tempconv selftest: ok (0C=32F=273.15K, 100C=212F, -40 crossover)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="tempconv",
        description="Temperature converter (Celsius, Fahrenheit, Kelvin, Rankine) with a table.")
    p.add_argument("value", nargs="?", type=float, help="temperature value")
    p.add_argument("from_unit", nargs="?", default="C", help="unit of VALUE (default C)")
    p.add_argument("--to", help="convert to this unit only (C, F, K, R)")
    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.value is None:
        p.error("VALUE is required")
    fu = UNITS.get(a.from_unit.lower(), a.from_unit.upper())
    if fu not in ("C", "F", "K", "R"):
        print(f"tempconv: unknown unit {a.from_unit!r} (use C, F, K or R)", file=sys.stderr)
        return 2
    k = to_k(a.value, fu)
    if k < 0:
        print(f"tempconv: warning: {a.value:g} {fu} is below absolute zero", file=sys.stderr)
    if a.to:
        tu = UNITS.get(a.to.lower(), a.to.upper())
        if tu not in ("C", "F", "K", "R"):
            print(f"tempconv: unknown unit {a.to!r}", file=sys.stderr); return 2
        print(f"{a.value:g} {fu} = {from_k(k, tu):g} {tu}")
        return 0
    print(f"{a.value:g} {fu}")
    for u in ("C", "F", "K", "R"):
        print(f"  {u}: {from_k(k, u):g}")
    return 0

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