#!/usr/bin/env python3
"""sortuniq — sort and dedupe a file in place, with a backup.
Usage: sortuniq [--no-backup] [--ignore-case] [--reverse] FILE
sort -u with a safety net: the original is kept as FILE.bak, and the report
says how many duplicate lines were dropped and how many lines remain.
"""
import argparse, sys


def main(argv=None):
    ap = argparse.ArgumentParser(prog="sortuniq",
        description="Sort and dedupe a file in place, with a backup.")
    ap.add_argument("file", help="file to sort and dedupe")
    ap.add_argument("--no-backup", action="store_true", help="do not keep a .bak copy")
    ap.add_argument("--ignore-case", action="store_true", help="case-insensitive sort/dedupe")
    ap.add_argument("--reverse", action="store_true", help="reverse sort order")
    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()
    try:
        with open(a.file, encoding="utf-8", errors="surrogateescape") as fh:
            text = fh.read()
    except OSError as e:
        print(f"sortuniq: {e}", file=sys.stderr)
        return 1
    had_final_nl = text.endswith("\n") or text == ""
    lines = text.splitlines()
    before = len(lines)
    key = (lambda s: s.lower()) if a.ignore_case else None
    ordered = sorted(lines, key=key, reverse=a.reverse)
    deduped = []
    seen = set()
    for line in ordered:
        k = line.lower() if a.ignore_case else line
        if k in seen:
            continue
        seen.add(k)
        deduped.append(line)
    out = "\n".join(deduped)
    if deduped and had_final_nl:
        out += "\n"
    if not a.no_backup:
        with open(a.file + ".bak", "w", encoding="utf-8", errors="surrogateescape") as fh:
            fh.write(text)
    with open(a.file, "w", encoding="utf-8", errors="surrogateescape") as fh:
        fh.write(out)
    print(f"sortuniq: {a.file}: {before} -> {len(deduped)} lines "
          f"({before - len(deduped)} duplicate(s) removed)"
          + ("" if a.no_backup else ", backup in " + a.file + ".bak"))
    return 0


def selftest():
    import tempfile, os
    with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
        fh.write("banana\napple\nbanana\nCherry\napple\n")
        path = fh.name
    try:
        assert main([path]) == 0
        assert open(path).read() == "Cherry\napple\nbanana\n", open(path).read()
        assert open(path + ".bak").read().count("banana") == 2
        open(path, "w").write("b\nA\nb\na\n")
        assert main(["--ignore-case", "--no-backup", path]) == 0
        assert open(path).read() == "A\nb\n", open(path).read()
    finally:
        for p in (path, path + ".bak"):
            if os.path.exists(p):
                os.unlink(p)
    print("sortuniq selftest: PASS")
    return 0


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