#!/usr/bin/env python3
"""wordfreq — word frequency histogram with stopword filtering and a top-N bar chart.
Usage: wordfreq [-n N] [--keep-stopwords] [--min-len L] [FILE ...]
Reads stdin when no FILE is given. The bar chart scales to the top count, so the
shape — not just the ranking — shows how dominant the top words are.
"""
import argparse, collections, re, sys

STOPWORDS = set("""a an the and or but if then else for of to in on at by with from as is are was were be been being have has had do does did will would shall should can could may might must i you he she it we they this that these those there here what when where who whom how why not no yes so than too very just into over under out up down all any each few more most other some such only own same""".split())
WORD_RE = re.compile(r"[A-Za-z][A-Za-z'\-]*")
BAR = "\u2588"


def tokenize(text, case_sensitive=False):
    if not case_sensitive:
        text = text.lower()
    return WORD_RE.findall(text)


def count_words(texts, keep_stopwords=False, min_len=1, case_sensitive=False):
    counts, total = collections.Counter(), 0
    for text in texts:
        words = tokenize(text, case_sensitive)
        total += len(words)
        for w in words:
            if len(w) < min_len:
                continue
            if not keep_stopwords and w.lower() in STOPWORDS:
                continue
            counts[w] += 1
    return counts, total


def main(argv=None):
    ap = argparse.ArgumentParser(prog="wordfreq",
        description="Word frequency histogram with stopword filtering and a top-N bar chart.")
    ap.add_argument("files", nargs="*", help="text files to analyse (default: stdin)")
    ap.add_argument("-n", "--top", type=int, default=20, help="show the top N words (default 20)")
    ap.add_argument("--keep-stopwords", action="store_true", help="do not filter common stopwords")
    ap.add_argument("--min-len", type=int, default=1, help="ignore words shorter than L letters")
    ap.add_argument("--case-sensitive", action="store_true", help="treat Cat and cat as different words")
    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()
    texts = []
    if a.files:
        for f in a.files:
            try:
                with open(f, encoding="utf-8", errors="replace") as fh:
                    texts.append(fh.read())
            except OSError as e:
                print(f"wordfreq: {e}", file=sys.stderr)
                return 1
    else:
        texts.append(sys.stdin.read())
    counts, total = count_words(texts, a.keep_stopwords, a.min_len, a.case_sensitive)
    kept = sum(counts.values())
    print(f"words: {total} total, {kept} counted, {len(counts)} distinct")
    if not counts:
        return 0
    top = counts.most_common(a.top)
    peak = top[0][1]
    width = max(len(w) for w, _ in top)
    for word, n in top:
        bar = BAR * max(1, round(n / peak * 40))
        print(f"{word:<{width}} {n:6d} {100.0 * n / kept:5.1f}% {bar}")
    return 0


def selftest():
    import io, tempfile, os
    from contextlib import redirect_stdout
    counts, total = count_words(["the cat sat on the mat the cat"], False, 1, False)
    assert total == 8 and counts.most_common(1)[0] == ("cat", 2), counts
    assert "the" not in counts, "stopword leaked through"
    with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:
        fh.write("apple banana apple cherry banana apple\n")
        path = fh.name
    try:
        buf = io.StringIO()
        with redirect_stdout(buf):
            rc = main(["-n", "2", path])
        out = buf.getvalue()
        assert rc == 0 and "apple" in out and "banana" in out, out
    finally:
        os.unlink(path)
    print("wordfreq selftest: PASS")
    return 0


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