#!/usr/bin/env python3
"""loghist — histogram of log events by hour, parsed from timestamps.
Usage: loghist [--by hour|day] [--level LEVEL] [FILE]
Reads stdin when no FILE is given. Pulls timestamps out of each log line and
draws a bar chart of events per hour (or per day), so bursts, quiet nights,
and the 3 a.m. error storm are visible at a glance instead of buried in text.
"""
import argparse, collections, re, sys
from datetime import datetime

BAR = "\u2588"
MONTHS = {m: i for i, m in enumerate(
    ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], 1)}
TS_RES = [
    (re.compile(r"(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):\d{2}"), lambda m: (int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)))),
    (re.compile(r"([A-Z][a-z]{2})\s+(\d{1,2}) (\d{2}):\d{2}"), lambda m: (datetime.now().year, MONTHS[m.group(1)], int(m.group(2)), int(m.group(3)))),
    (re.compile(r"(\d{2})/([A-Z][a-z]{2})/(\d{4}):(\d{2}):\d{2}"), lambda m: (int(m.group(3)), MONTHS[m.group(2)], int(m.group(1)), int(m.group(4)))),
]


def parse_ts(line):
    for rx, build in TS_RES:
        m = rx.search(line)
        if m:
            try:
                y, mo, d, h = build(m)
                return datetime(y, mo, d, h)
            except ValueError:
                continue
    return None


def histogram(lines, by="hour"):
    buckets = collections.Counter()
    parsed = unparsed = 0
    for line in lines:
        ts = parse_ts(line)
        if ts is None:
            unparsed += 1
            continue
        parsed += 1
        key = ts.strftime("%Y-%m-%d %H:00") if by == "hour" else ts.strftime("%Y-%m-%d")
        buckets[key] += 1
    return buckets, parsed, unparsed


def main(argv=None):
    ap = argparse.ArgumentParser(prog="loghist",
        description="Histogram of log events by hour, parsed from timestamps.")
    ap.add_argument("file", nargs="?", help="log file (default: stdin)")
    ap.add_argument("--by", default="hour", choices=["hour", "day"], help="bucket size (default hour)")
    ap.add_argument("--level", help="only count lines containing this level, e.g. ERROR")
    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:
        lines = open(a.file, encoding="utf-8", errors="replace").readlines() if a.file else sys.stdin.readlines()
    except OSError as e:
        print(f"loghist: {e}", file=sys.stderr)
        return 1
    if a.level:
        lines = [l for l in lines if a.level in l]
    buckets, parsed, unparsed = histogram(lines, a.by)
    if not buckets:
        print("loghist: no parseable timestamps found", file=sys.stderr)
        return 1
    peak = max(buckets.values())
    total = sum(buckets.values())
    print(f"loghist: {total} event(s) in {len(buckets)} bucket(s); peak {peak} at "
          f"{max(buckets, key=buckets.get)}" + (f"; {unparsed} line(s) without timestamps" if unparsed else ""))
    for key in sorted(buckets):
        n = buckets[key]
        print(f"{key} {n:6d} {BAR * max(1, round(n / peak * 40))}")
    return 0


def selftest():
    import tempfile, os, io
    from contextlib import redirect_stdout
    data = ("2026-12-03 10:00:01 INFO a\n2026-12-03 10:15:00 INFO b\n"
            "2026-12-03 11:00:00 ERROR c\n2026-12-03 11:30:00 INFO d\n"
            "2026-12-03 11:45:00 INFO e\nno timestamp here\n")
    buckets, parsed, unparsed = histogram(data.splitlines())
    assert buckets == {"2026-12-03 10:00": 2, "2026-12-03 11:00": 3}, buckets
    assert parsed == 5 and unparsed == 1, (parsed, unparsed)
    with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as fh:
        fh.write(data)
        path = fh.name
    try:
        buf = io.StringIO()
        with redirect_stdout(buf):
            rc = main(["--level", "ERROR", path])
        assert rc == 0 and "11:00" in buf.getvalue() and "1 event(s)" in buf.getvalue(), buf.getvalue()
    finally:
        os.unlink(path)
    print("loghist selftest: PASS")
    return 0


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