#!/usr/bin/env python3
"""encfix — detect and convert text encodings (UTF-8/16, latin-1) with a report.
Usage: encfix [--to utf-8|utf-16|latin-1] [--in-place] [FILE ...]
Reads stdin when no FILE is given. Detects BOMs, validates UTF-8, falls back to
UTF-16 and latin-1, and reports what each file actually is — then converts the
lot to one encoding so the next tool in the chain stops choking on mojibake.
"""
import argparse, sys

CANDIDATES = ["utf-8", "utf-16", "latin-1"]


def detect(raw):
    if raw.startswith(b"\xef\xbb\xbf"):
        return "utf-8-sig", "BOM"
    if raw.startswith(b"\xff\xfe"):
        return "utf-16-le", "BOM"
    if raw.startswith(b"\xfe\xff"):
        return "utf-16-be", "BOM"
    try:
        raw.decode("utf-8")
        return "utf-8", "valid UTF-8"
    except UnicodeDecodeError:
        pass
    try:
        text = raw.decode("utf-16")
        # UTF-16 decodes almost anything; only trust it if it looks like text:
        # mostly printable, with a plausible share of NULs from the high bytes.
        if text and sum(1 for c in text if c.isprintable() or c in "\n\r\t") / len(text) > 0.9:
            return "utf-16", "decoded as UTF-16, printable"
    except UnicodeDecodeError:
        pass
    return "latin-1", "assumed (not valid UTF-8)"


def decode(raw, encoding):
    if encoding in ("utf-8-sig", "utf-8"):
        return raw.decode("utf-8-sig")
    if encoding == "utf-16-le":
        return raw[2:].decode("utf-16-le")
    if encoding == "utf-16-be":
        return raw[2:].decode("utf-16-be")
    if encoding == "utf-16":
        return raw.decode("utf-16")
    return raw.decode("latin-1")


def main(argv=None):
    ap = argparse.ArgumentParser(prog="encfix",
        description="Detect and convert text encodings (UTF-8/16, latin-1) with a report.")
    ap.add_argument("files", nargs="*", help="files to check (default: stdin)")
    ap.add_argument("--to", default="utf-8", choices=["utf-8", "utf-16", "latin-1"],
                    help="target encoding (default utf-8)")
    ap.add_argument("--in-place", action="store_true", help="rewrite files in the target encoding")
    ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    argv_list = list(argv) if argv is not None else sys.argv[1:]
    if "--selftest" in argv_list:
        return selftest()
    a = ap.parse_args(argv)
    if a.selftest:
        return selftest()
    if not a.files:
        raw = sys.stdin.buffer.read()
        enc, how = detect(raw)
        print(f"<stdin>: {enc} ({how})", file=sys.stderr)
        sys.stdout.write(decode(raw, enc).encode(a.to, errors="replace").decode(a.to, errors="replace"))
        return 0
    bad = 0
    for path in a.files:
        try:
            raw = open(path, "rb").read()
        except OSError as e:
            print(f"encfix: {e}", file=sys.stderr)
            return 1
        enc, how = detect(raw)
        text = decode(raw, enc)
        changed = enc != a.to and not (enc in ("utf-8-sig", "utf-8") and a.to == "utf-8")
        if enc != "utf-8":
            bad += 1
        print(f"{path}: {enc} ({how})" + ("  -> would convert to " + a.to if changed and not a.in_place else ""))
        if a.in_place and changed:
            open(path, "wb").write(text.encode(a.to))
            print(f"  -> converted to {a.to}")
    return 0


def selftest():
    import tempfile, os
    assert detect("plain ascii".encode())[0] == "utf-8"
    assert detect("caf\u00e9".encode("utf-16"))[0].startswith("utf-16")
    assert detect("caf\u00e9".encode("latin-1"))[0] == "latin-1"
    assert detect(b"\xef\xbb\xbfhi")[0] == "utf-8-sig"
    with tempfile.TemporaryDirectory() as d:
        p1 = os.path.join(d, "u16.txt")
        open(p1, "wb").write("hello w\u00f6rld".encode("utf-16"))
        p2 = os.path.join(d, "lat.txt")
        open(p2, "wb").write("caf\u00e9".encode("latin-1"))
        assert main([p1, p2]) == 0
        assert main(["--in-place", p1, p2]) == 0
        assert open(p1, encoding="utf-8").read() == "hello w\u00f6rld"
        assert open(p2, encoding="utf-8").read() == "caf\u00e9"
    print("encfix selftest: PASS")
    return 0


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