import logging
import sys

if 'code' in sys.modules:
    del sys.modules['code']
from code.justin.tv.dta.rockpaperscissors import environment
from code.justin.tv.dta.rockpaperscissors import errors
from code.justin.tv.dta.rockpaperscissors import event_bus


logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.getLogger('boto3').setLevel(logging.WARNING)
logging.getLogger('botocore').setLevel(logging.WARNING)


def lambda_handler(event, context):
    logger.info('Processing %d records', len(event['Records']))

    env = environment.GetEnvironment(context)
    store = env.EventStore()

    # Undecodable or invalid events are logged and skipped.
    events = filter(
      bool, (EventFromRecord(record) for record in event['Records']))
    if events:
        store.PutEvents(events)


def EventFromRecord(record):
    try:
        return event_bus.DecodeKinesisRecordData(record['kinesis']['data'])
    except (errors.EventDecodeError, errors.EventInvalid) as e:
        logger.error(str(e))
        return
