#!/usr/bin/env python3
"""logtail — tail a log with colorized levels and a lines-per-second rate meter.
Usage: logtail [-n N] [--follow] [--seconds S] FILE
Like tail, but ERROR/WARN/INFO/DEBUG levels get colours, and the header reports
the event rate (lines/sec) measured from the timestamps in the file — so you see
at a glance whether the log is idle or on fire.
"""
import argparse, re, sys, time
from datetime import datetime

RED = "\033[31m"
YELLOW = "\033[33m"
GREEN = "\033[32m"
DIM = "\033[2m"
RESET = "\033[0m"
LEVELS = [("ERROR", RED), ("CRITICAL", RED), ("FATAL", RED), ("WARN", YELLOW),
          ("WARNING", YELLOW), ("INFO", GREEN), ("DEBUG", DIM), ("TRACE", DIM)]
TS_RES = [
    re.compile(r"(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?)"),
    re.compile(r"(\d{2}:\d{2}:\d{2})"),
]


def parse_ts(line):
    for rx in TS_RES:
        m = rx.search(line)
        if not m:
            continue
        s = m.group(1)
        for fmt in ("%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S.%f",
                    "%Y-%m-%d %H:%M:%S", "%H:%M:%S"):
            try:
                return datetime.strptime(s, fmt)
            except ValueError:
                continue
    return None


def colorize(line, color=True):
    if not color:
        return line
    for name, code in LEVELS:
        if name in line:
            return code + line + RESET
    return line


def rate_of(lines):
    stamps = [t for t in (parse_ts(l) for l in lines) if t is not None]
    if len(stamps) < 2:
        return None
    span = (stamps[-1] - stamps[0]).total_seconds()
    if span <= 0:
        return None
    return len(lines) / span, span


def tail_lines(path, n):
    with open(path, encoding="utf-8", errors="replace") as fh:
        buf = []
        for line in fh:
            buf.append(line)
            if len(buf) > n:
                buf.pop(0)
    return buf


def main(argv=None):
    ap = argparse.ArgumentParser(prog="logtail",
        description="Tail a log with colorized levels and a lines-per-second rate meter.")
    ap.add_argument("file", help="log file to tail")
    ap.add_argument("-n", "--lines", type=int, default=50, help="lines to show (default 50)")
    ap.add_argument("--follow", action="store_true", help="keep following new lines (like tail -f)")
    ap.add_argument("--seconds", type=float, default=0, help="with --follow, stop after S seconds")
    ap.add_argument("--no-color", action="store_true", help="disable colours")
    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()
    color = not a.no_color and sys.stdout.isatty()
    try:
        lines = tail_lines(a.file, a.lines)
    except OSError as e:
        print(f"logtail: {e}", file=sys.stderr)
        return 1
    rate = rate_of(lines)
    if rate:
        print(f"logtail: {a.file} — {len(lines)} lines, {rate[0]:.2f} lines/s over {rate[1]:.0f}s",
              file=sys.stderr)
    else:
        print(f"logtail: {a.file} — {len(lines)} lines (no parseable timestamps for a rate)",
              file=sys.stderr)
    for line in lines:
        sys.stdout.write(colorize(line.rstrip("\n"), color) + "\n")
    if a.follow:
        seen = 0
        start = time.time()
        with open(a.file, encoding="utf-8", errors="replace") as fh:
            fh.seek(0, 2)
            while True:
                line = fh.readline()
                if line:
                    seen += 1
                    sys.stdout.write(colorize(line.rstrip("\n"), color) + "\n")
                    sys.stdout.flush()
                else:
                    if a.seconds and time.time() - start >= a.seconds:
                        break
                    time.sleep(0.2)
        print(f"logtail: followed {seen} new line(s)", file=sys.stderr)
    return 0


def selftest():
    import tempfile, os
    data = ("2026-12-03 10:00:00 INFO server started\n"
            "2026-12-03 10:00:01 WARN disk 80% full\n"
            "2026-12-03 10:00:02 ERROR connection refused\n"
            "2026-12-03 10:00:04 INFO retry ok\n")
    with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as fh:
        fh.write(data)
        path = fh.name
    try:
        lines = tail_lines(path, 10)
        assert len(lines) == 4, lines
        rate = rate_of(lines)
        assert rate is not None and abs(rate[0] - 1.0) < 0.01, rate
        assert "\033[31m" in colorize("x ERROR y") and "\033[33m" in colorize("x WARN y")
        assert main(["-n", "2", "--no-color", path]) == 0
    finally:
        os.unlink(path)
    print("logtail selftest: PASS")
    return 0


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