#!/usr/bin/python3
import argparse
import perg, _enum, sample

        
# A generator of (roughly) uniform samples from the set of strings matching the regex
# NOTE: This is not actually a uniform sample, for the following reasons
#   - For 'at least n times' patterns, interval [n, inf) is sampled using a geometric distribution
#   - Not sure whether the entire set of matches is actually generable using this scheme 
#     for all regexes.. 
def sampler(s, e=False):
    tree = perg.parse(s)
    if e:
        for f in enum.enum_gen(tree):
            yield f
    else:
        while True:
            yield sample.sample(tree)
        

# Commandline execution
if __name__ == '__main__':  

    # CLI opts
    parser = argparse.ArgumentParser(description="Generate a stream of random samples from the set of strings matching your regex")
    parser.add_argument('regex', help='regex to sample matches from')
    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument('-n', help='number of matches to sample', type=int, default=0)
    group.add_argument('-e', help='enumerate all matches', action='store_true')

    args = parser.parse_args()

    # Get regex to sample from as 1st arg
    regex = args.regex.replace('\\\\', '\\') 

    # If no -n arg, sample forever
    if not args.n:
        for s in sampler(regex, e=args.e):
            print(s)
    else:
        generator = sampler(regex)
        for _ in range(args.n):
            print(next(generator))
