#!/usr/bin/env python3
# bin2txt — encode a binary file as text (base64/hex) with a decode header (magic, algo, original name/size, sha256).
# Usage: bin2txt [--hex] [--wrap N] input [output.txt]
"""bin2txt: binary-to-text with a self-describing header. The output starts
with `# bin2txt v1` plus algorithm, original filename, size and SHA-256, so
the matching txt2bin can decode it and verify the result — safe to paste into
email, tickets, or chat without losing track of what it was."""
import argparse, base64, hashlib, os, sys

HEADER = "# bin2txt v1"

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for c in iter(lambda: f.read(65536), b""): h.update(c)
    return h.hexdigest()

def encode(inp, out, algo="base64", wrap=76):
    data = open(inp, "rb").read()
    body = data.hex() if algo == "hex" else base64.b64encode(data).decode()
    lines = [f"{HEADER}", f"# algo: {algo}", f"# filename: {os.path.basename(inp)}",
             f"# size: {len(data)}", f"# sha256: {sha256(inp)}", "#"]
    if wrap:
        lines += [body[i:i+wrap] for i in range(0, len(body), wrap)]
    else:
        lines.append(body)
    text = "\n".join(lines) + "\n"
    if out: open(out, "w").write(text)
    else: sys.stdout.write(text)
    print(f"bin2txt: {len(data)} bytes -> {algo}, sha256 {sha256(inp)[:16]}...", file=sys.stderr)
    return 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        src = os.path.join(d, "a.bin"); open(src, "wb").write(bytes(range(256)) * 4)
        out = os.path.join(d, "a.txt")
        assert encode(src, out) == 0
        head = open(out).read().splitlines()
        assert head[0] == HEADER and head[1] == "# algo: base64"
        assert head[3] == "# size: 1024"
        out2 = os.path.join(d, "b.txt")
        assert encode(src, out2, algo="hex", wrap=0) == 0
        assert open(out2).read().splitlines()[1] == "# algo: hex"
    print("bin2txt selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Encode a binary file as text with a decode header (magic, algo, name, size, sha256).")
    ap.add_argument("input", nargs="?"); ap.add_argument("output", nargs="?")
    ap.add_argument("--hex", action="store_true", help="use hex instead of base64")
    ap.add_argument("--wrap", type=int, default=76, help="wrap body at N columns (0 = no wrap)")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.input: ap.error("need an input file")
    return encode(a.input, a.output, "hex" if a.hex else "base64", a.wrap)

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