#!/usr/bin/env python3
# bomfix — detect, strip, or add a BOM (UTF-8/16/32) in text files, reporting what each file had.
# Usage: bomfix [--strip] [--add utf-8|utf-16le|utf-16be|utf-32le] [--recursive] file|dir [...]
"""bomfix: end the BOM guessing game. It scans files, reports which BOM (if
any) each one carries, strips BOMs that break tools, or adds the BOM a Windows
tool expects — with a per-file before/after report instead of silent edits."""
import argparse, os, sys

BOMS = [(b"\xef\xbb\xbf", "UTF-8"), (b"\xff\xfe\x00\x00", "UTF-32LE"), (b"\x00\x00\xfe\xff", "UTF-32BE"),
        (b"\xff\xfe", "UTF-16LE"), (b"\xfe\xff", "UTF-16BE")]
ADD = {"utf-8": b"\xef\xbb\xbf", "utf-16le": b"\xff\xfe", "utf-16be": b"\xfe\xff",
       "utf-32le": b"\xff\xfe\x00\x00", "utf-32be": b"\x00\x00\xfe\xff"}

def detect(data):
    for bom, name in BOMS:
        if data.startswith(bom): return name, len(bom)
    return None, 0

def collect(targets, recursive):
    paths = []
    for t in targets:
        if os.path.isdir(t):
            for root, _, files in os.walk(t):
                for f in files: paths.append(os.path.join(root, f))
                if not recursive: break
        elif os.path.isfile(t): paths.append(t)
    return paths

def run(targets, mode, add_enc=None, recursive=False):
    paths = collect(targets, recursive)
    changed = 0
    for p in paths:
        try: data = open(p, "rb").read()
        except OSError as e: print(f"bomfix: {p}: {e}", file=sys.stderr); continue
        name, n = detect(data)
        if mode == "detect":
            print(f"{name or 'no BOM':<8} {p}")
        elif mode == "strip":
            if name:
                open(p, "wb").write(data[n:])
                print(f"stripped {name} BOM: {p}"); changed += 1
            else: print(f"no BOM: {p}")
        elif mode == "add":
            bom = ADD[add_enc]
            if name:
                print(f"already has {name} BOM: {p} (left alone)")
            else:
                open(p, "wb").write(bom + data)
                print(f"added {add_enc} BOM: {p}"); changed += 1
    if mode != "detect": print(f"bomfix: {changed} file(s) changed")
    return 0

def selftest():
    import tempfile, os
    with tempfile.TemporaryDirectory() as d:
        a = os.path.join(d, "a.txt"); open(a, "wb").write(b"\xef\xbb\xbfhello\n")
        b = os.path.join(d, "b.txt"); open(b, "w").write("plain\n")
        assert run([a, b], "detect") == 0
        assert run([a], "strip") == 0
        assert open(a, "rb").read() == b"hello\n"
        assert run([b], "add", "utf-8") == 0
        assert open(b, "rb").read().startswith(b"\xef\xbb\xbf")
    print("bomfix selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Detect, strip, or add a BOM (UTF-8/16/32) in text files.")
    ap.add_argument("targets", nargs="*", default=["."])
    ap.add_argument("--strip", action="store_true")
    ap.add_argument("--add", choices=list(ADD), help="add this BOM")
    ap.add_argument("--recursive", "-r", action="store_true")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    mode = "strip" if a.strip else ("add" if a.add else "detect")
    return run(a.targets, mode, a.add, a.recursive)

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