#!/usr/bin/env python3
"""textclean — normalize text: trim trailing whitespace, fix line endings, collapse blanks, ensure final newline.
Usage: textclean [--in-place] [--check] [--max-blanks N] [FILE ...]
One pass that makes a text file boringly well-formed. Default prints the cleaned
text to stdout; --in-place rewrites files and reports what changed per file.
"""
import argparse, sys


def clean_text(text, max_blanks=1):
    fixes = {"crlf": 0, "cr": 0, "trailing_ws": 0, "blank_runs": 0, "final_newline": 0}
    fixes["crlf"] = text.count("\r\n")
    text = text.replace("\r\n", "\n")
    fixes["cr"] = text.count("\r")
    text = text.replace("\r", "\n")
    out, blanks = [], 0
    for line in text.split("\n"):
        stripped = line.rstrip(" \t")
        if stripped != line:
            fixes["trailing_ws"] += 1
        if stripped == "":
            blanks += 1
            if blanks > max_blanks:
                fixes["blank_runs"] += 1
                continue
            out.append("")
        else:
            blanks = 0
            out.append(stripped)
    text = "\n".join(out)
    if text and not text.endswith("\n"):
        text += "\n"
        fixes["final_newline"] += 1
    elif not text:
        text = ""
    return text, fixes


def main(argv=None):
    ap = argparse.ArgumentParser(prog="textclean",
        description="Normalize text: trim trailing whitespace, fix line endings, collapse blanks, ensure final newline.")
    ap.add_argument("files", nargs="*", help="files to clean (default: stdin to stdout)")
    ap.add_argument("--in-place", action="store_true", help="rewrite files instead of printing")
    ap.add_argument("--check", action="store_true", help="exit 1 if any file would change; change nothing")
    ap.add_argument("--max-blanks", type=int, default=1, help="max consecutive blank lines (default 1)")
    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:
        if a.in_place or a.check:
            print("textclean: --in-place/--check need file arguments", file=sys.stderr)
            return 2
        cleaned, _ = clean_text(sys.stdin.read(), a.max_blanks)
        sys.stdout.write(cleaned)
        return 0
    dirty = 0
    for path in a.files:
        try:
            with open(path, encoding="utf-8", errors="surrogateescape") as fh:
                orig = fh.read()
        except OSError as e:
            print(f"textclean: {e}", file=sys.stderr)
            return 1
        cleaned, fixes = clean_text(orig, a.max_blanks)
        changed = cleaned != orig
        if changed:
            dirty += 1
        summary = ", ".join(f"{k}={v}" for k, v in fixes.items() if v)
        if a.check:
            print(f"{path}: {'WOULD CHANGE' + (' (' + summary + ')') if changed else 'clean'}")
            continue
        if a.in_place:
            if changed:
                with open(path, "w", encoding="utf-8", errors="surrogateescape") as fh:
                    fh.write(cleaned)
                print(f"{path}: cleaned ({summary})")
            else:
                print(f"{path}: already clean")
        else:
            sys.stdout.write(cleaned)
    return 1 if (a.check and dirty) else 0


def selftest():
    import tempfile, os
    dirty = "hello   \r\nworld\t\r\n\r\n\r\n\r\nno newline at end"
    cleaned, fixes = clean_text(dirty, 1)
    assert cleaned == "hello\nworld\n\nno newline at end\n", repr(cleaned)
    assert fixes["crlf"] == 5 and fixes["trailing_ws"] == 2 and fixes["final_newline"] == 1, fixes
    assert clean_text("already\nclean\n")[0] == "already\nclean\n"
    with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
        fh.write(dirty)
        path = fh.name
    try:
        assert main(["--check", path]) == 1
        assert main(["--in-place", path]) == 0
        assert open(path).read() == cleaned
        assert main(["--check", path]) == 0
    finally:
        os.unlink(path)
    print("textclean selftest: PASS")
    return 0


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