#!/usr/bin/env python
import sys
import time
import logging
import argparse

import github_watcher
import github_watcher.run
import github_watcher.config


action_help = '''
run|config - *run* Runs the daemon. Watches files and alerts when there is a pull request of interest.
             *config* Is a convenience tool to help you configure the watcher. You
              can add line ranges or directories, update the API url,
              or add new files to watch.
'''


parser = argparse.ArgumentParser(description='')
parser.add_argument('action', default='run', help=action_help)
parser.add_argument('--verbose', dest='verbose', action='store_true', default=False)
args = parser.parse_args()

logger = logging.getLogger()
logger.setLevel(logging.DEBUG if args.verbose else logging.ERROR)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - L%(lineno)d %(message)s'))
logger.addHandler(handler)

THROTTLE_THRESHOLD = 600 # seconds
backoff = 1
if args.action == 'run':
    while True:
        try:
            last_invokation = time.time()
            github_watcher.run.main()
        except KeyboardInterrupt:
            sys.exit(0)
        except Exception as e:
            if time.time() - last_invokation > THROTTLE_THRESHOLD:
                logger.exception(e)
                logger.error('Backing off {} seconds'.format(backoff))
                backoff *= 2
            else:
                backoff = 1
            time.sleep(backoff)
            continue
elif args.action == 'config':
    github_watcher.config.main()
else:
    parser.print_help()
    sys.exit(1)
