#!/usr/bin/env python3
"""randline — pick N random lines from a file.
Usage: randline [-n N] [--seed S] [--with-replacement] [FILE]
Reservoir sampling: every line has an equal chance, and the whole file is never
held in memory — it works on gigabyte logs. --seed makes the pick reproducible.
"""
import argparse, random, sys


def reservoir(fh, n, rng, with_replacement):
    if with_replacement:
        pool = []
        for line in fh:
            pool.append(line)
            if len(pool) > 100000:
                # keep memory bounded: thin the pool by random eviction
                pool = [pool[i] for i in sorted(rng.sample(range(len(pool)), 10000))]
        if not pool:
            return []
        return [rng.choice(pool) for _ in range(n)]
    chosen = []
    for i, line in enumerate(fh):
        if i < n:
            chosen.append(line)
        else:
            j = rng.randint(0, i)
            if j < n:
                chosen[j] = line
    return chosen


def main(argv=None):
    ap = argparse.ArgumentParser(prog="randline",
        description="Pick N random lines from a file (reservoir sampling; equal odds, bounded memory).")
    ap.add_argument("file", nargs="?", help="file to sample (default: stdin)")
    ap.add_argument("-n", "--count", type=int, default=1, help="lines to pick (default 1)")
    ap.add_argument("--seed", type=int, help="random seed for a reproducible pick")
    ap.add_argument("--with-replacement", action="store_true", help="allow the same line twice")
    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()
    if a.count < 0:
        print("randline: -n must be >= 0", file=sys.stderr)
        return 2
    rng = random.Random(a.seed)
    try:
        fh = open(a.file, encoding="utf-8", errors="replace") if a.file else sys.stdin
        with fh:
            picked = reservoir(fh, a.count, rng, a.with_replacement)
    except OSError as e:
        print(f"randline: {e}", file=sys.stderr)
        return 1
    for line in picked:
        sys.stdout.write(line if line.endswith("\n") else line + "\n")
    return 0


def selftest():
    import io
    rng = random.Random(42)
    lines = [f"l{i}\n" for i in range(100)]
    pick1 = reservoir(iter(lines), 5, random.Random(7), False)
    pick2 = reservoir(iter(lines), 5, random.Random(7), False)
    assert pick1 == pick2, "same seed must give same pick"
    assert len(pick1) == 5 and len(set(pick1)) == 5, pick1
    assert all(p in lines for p in pick1)
    small = reservoir(iter(["a\n", "b\n"]), 10, random.Random(1), False)
    assert len(small) == 2, small
    rep = reservoir(iter(lines), 5, random.Random(3), True)
    assert len(rep) == 5
    print("randline selftest: PASS")
    return 0


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