#!/usr/bin/env python3
"""badlines — find overlong lines, trailing whitespace, and tabs: a lint for text files.
Usage: badlines [--max-len N] [--no-tabs] [--no-trailing] [FILE ...]
Reads stdin when no FILE is given. Reports file:line:issue for every offending
line, with a per-file summary. Exit 0 when clean, 1 when issues are found, so
it drops straight into a pre-commit hook or CI check.
"""
import argparse, sys


def lint_text(text, max_len=100, check_tabs=True, check_trailing=True):
    issues = []
    lines = text.split("\n")
    for i, line in enumerate(lines, 1):
        if i == len(lines) and line == "":
            break  # trailing newline is not a line
        if len(line) > max_len:
            issues.append((i, f"line too long ({len(line)} > {max_len} chars)"))
        if check_trailing and line != line.rstrip(" \t"):
            issues.append((i, "trailing whitespace"))
        if check_tabs and "\t" in line:
            issues.append((i, "contains tab(s)"))
    if text and not text.endswith("\n"):
        issues.append((len(lines), "no final newline"))
    return issues


def main(argv=None):
    ap = argparse.ArgumentParser(prog="badlines",
        description="Find overlong lines, trailing whitespace, and tabs — a lint for text files.")
    ap.add_argument("files", nargs="*", help="files to lint (default: stdin)")
    ap.add_argument("--max-len", type=int, default=100, help="max line length (default 100)")
    ap.add_argument("--no-tabs", action="store_true", help="do not flag tabs")
    ap.add_argument("--no-trailing", action="store_true", help="do not flag trailing whitespace")
    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()
    total = 0
    sources = []
    if a.files:
        for path in a.files:
            try:
                sources.append((path, open(path, encoding="utf-8", errors="replace").read()))
            except OSError as e:
                print(f"badlines: {e}", file=sys.stderr)
                return 2
    else:
        sources.append(("<stdin>", sys.stdin.read()))
    for path, text in sources:
        issues = lint_text(text, a.max_len, not a.no_tabs, not a.no_trailing)
        for line_no, msg in issues:
            print(f"{path}:{line_no}: {msg}")
        if issues:
            print(f"{path}: {len(issues)} issue(s)", file=sys.stderr)
        total += len(issues)
    if total:
        print(f"badlines: {total} issue(s) total", file=sys.stderr)
        return 1
    print("badlines: clean", file=sys.stderr)
    return 0


def selftest():
    import tempfile, os
    good = "short line\nanother short line\n"
    assert lint_text(good) == []
    bad = "ok\n" + "x" * 101 + "\ntrailing   \n\ttabbed\nno newline"
    issues = lint_text(bad)
    kinds = [m for _, m in issues]
    assert any("too long" in m for m in kinds), kinds
    assert any("trailing whitespace" in m for m in kinds), kinds
    assert any("tab" in m for m in kinds), kinds
    assert any("no final newline" in m for m in kinds), kinds
    with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
        fh.write(good)
        p_good = fh.name
    with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
        fh.write(bad)
        p_bad = fh.name
    try:
        assert main([p_good]) == 0
        assert main([p_bad]) == 1
    finally:
        os.unlink(p_good)
        os.unlink(p_bad)
    print("badlines selftest: PASS")
    return 0


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