#!/usr/bin/env python
"""
Usage: merge [count] [FILE [FILE [FILE [...]]]]

This program merges multiple JSON scrape files into a single event stream,
with a maximum of 'count' elements.

By default, 'count' is 30.
"""

from __future__ import print_function

import json
import os
import sys

def main():
    if set(['-h', '--help']) & set(sys.argv):
        usage()
        sys.exit(1)

    count = 30

    try:
        count = int(sys.argv[1])
        sys.argv.pop(0)
    except (IndexError, ValueError):
        pass

    events = []

    for f in sys.argv[1:]:
        events.extend(json.load(open(f)))

    events.sort(key=lambda e: e['date'])

    print(json.dumps(events[-count:]))

def usage():
    print(__doc__, file=sys.stderr)

if __name__ == '__main__':
    main()

