#!/usr/bin/env python3
# dataconv - convert data sizes (B/KB/MB/GB, bits/bytes, MiB vs MB)
# Usage: dataconv VALUE UNIT [--to UNIT] [--bits]
#   With no --to, prints the value in every unit, decimal (MB) and binary (MiB).
#   Example: dataconv 1.5 GiB | dataconv 100 MB --to KiB | dataconv 8 Mbit --bits
import argparse, sys

DEC = {"bit": 0.125, "B": 1.0, "KB": 1e3, "MB": 1e6, "GB": 1e9, "TB": 1e12,
       "PB": 1e15, "EB": 1e18}
BIN = {"Kib": 128.0, "KiB": 1024.0, "MiB": 1024.0**2, "GiB": 1024.0**3,
       "TiB": 1024.0**4, "PiB": 1024.0**5, "EiB": 1024.0**6}
ALL = {**DEC, **BIN}
ALIASES = {"b": "bit", "bits": "bit", "byte": "B", "bytes": "B",
           "kib": "Kib", "mib": "MiB", "gib": "GiB", "tib": "TiB",
           "kb": "KB", "mb": "MB", "gb": "GB", "tb": "TB"}
# note: mbit/gbit aliases corrected below at lookup time
BIT_ALIASES = {"kbit": 125.0, "mbit": 125000.0, "gbit": 125000000.0, "tbit": 125000000000.0}

def norm(u):
    if u in BIT_ALIASES or u in ALL:
        return u
    return ALIASES.get(u.lower(), ALIASES.get(u, u))

def to_bytes(v, u):
    if u in BIT_ALIASES:
        return v * BIT_ALIASES[u]
    if u not in ALL:
        raise ValueError(f"unknown unit {u!r}")
    return v * ALL[u]

def selftest():
    assert to_bytes(1, "KiB") == 1024
    assert to_bytes(1, "KB") == 1000
    assert abs(to_bytes(1.5, "GiB") - 1610612736) < 1
    assert to_bytes(8, "bit") == 1
    assert abs(to_bytes(1, "MB") / to_bytes(1, "MiB") - 0.95367431640625) < 1e-12
    print("dataconv selftest: ok (KiB=1024, KB=1000, bits/bytes, MiB vs MB)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="dataconv",
        description="Convert data sizes: decimal vs binary units, bits vs bytes.")
    p.add_argument("value", nargs="?", type=float, help="value to convert")
    p.add_argument("unit", nargs="?", help="unit of the value (B, KB, MB, KiB, MiB, bit, ...)")
    p.add_argument("--to", dest="to", help="convert to this unit only")
    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 or not a.unit:
        p.error("VALUE and UNIT are required")
    u = norm(a.unit)
    try:
        b = to_bytes(a.value, u)
    except ValueError as e:
        print(f"dataconv: {e}", file=sys.stderr); return 2
    if a.to:
        t = norm(a.to)
        try:
            tb = to_bytes(1, t)
        except ValueError as e:
            print(f"dataconv: {e}", file=sys.stderr); return 2
        print(f"{a.value:g} {a.unit} = {b / tb:g} {a.to}")
        return 0
    print(f"{a.value:g} {a.unit} = {b:g} bytes ({b * 8:g} bits)")
    print("  decimal: " + "  ".join(f"{b / v:g} {k}" for k, v in DEC.items() if k != "bit"))
    print("  binary:  " + "  ".join(f"{b / v:g} {k}" for k, v in BIN.items()))
    return 0

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