#!/usr/bin/env python3
"""tailfollow — follow a file and show only lines matching a pattern, with running counts.
Usage: tailfollow [--from-start] [--timeout S] [--max-lines N] PATTERN FILE
tail -f piped through grep, with the counts grep never gives you: every
matching line is printed as it arrives, and on exit you get matched/total so
far — how much of the live stream actually matched, not just the hits.
"""
import argparse, re, sys, time


def main(argv=None):
    ap = argparse.ArgumentParser(prog="tailfollow",
        description="Follow a file and show only lines matching a pattern, with running counts.")
    ap.add_argument("pattern", help="regex to match (case-sensitive unless --ignore-case)")
    ap.add_argument("file", help="file to follow")
    ap.add_argument("--from-start", action="store_true", help="scan the whole file first, then follow")
    ap.add_argument("--timeout", type=float, default=0, help="stop after S seconds (0 = run until Ctrl-C)")
    ap.add_argument("--max-lines", type=int, default=0, help="stop after N matched lines (0 = unlimited)")
    ap.add_argument("--ignore-case", action="store_true", help="case-insensitive match")
    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:
        rx = re.compile(a.pattern, re.IGNORECASE if a.ignore_case else 0)
    except re.error as e:
        print(f"tailfollow: bad pattern: {e}", file=sys.stderr)
        return 2
    matched = total = 0
    start = time.time()
    try:
        with open(a.file, encoding="utf-8", errors="replace") as fh:
            if not a.from_start:
                fh.seek(0, 2)
            while True:
                line = fh.readline()
                if line:
                    total += 1
                    if rx.search(line):
                        matched += 1
                        sys.stdout.write(f"[{matched}] {line}" if not line.endswith("\n") else f"[{matched}] {line}")
                        sys.stdout.flush()
                        if a.max_lines and matched >= a.max_lines:
                            break
                else:
                    if a.timeout and time.time() - start >= a.timeout:
                        break
                    time.sleep(0.1)
    except OSError as e:
        print(f"tailfollow: {e}", file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        pass
    print(f"tailfollow: matched {matched} of {total} line(s) seen", file=sys.stderr)
    return 0


def selftest():
    import os, subprocess, sys, tempfile, time
    with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as fh:
        fh.write("INFO start\n")
        path = fh.name
    try:
        # Start the follower FIRST and give it a second to seek to EOF;
        # only then append, so the test cannot race interpreter startup.
        proc = subprocess.Popen([sys.executable, os.path.abspath(__file__),
                                 "--timeout", "4", "ERROR", path],
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        time.sleep(1.0)
        with open(path, "a") as fh:
            fh.write("ERROR boom\nINFO ok\nERROR again\n")
        out, err = proc.communicate(timeout=10)
        assert proc.returncode == 0, err
        assert "[1] ERROR boom" in out and "[2] ERROR again" in out, out
        assert "matched 2 of 3" in err, err
    finally:
        os.unlink(path)
    print("tailfollow selftest: PASS")
    return 0


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