#!/usr/bin/env python3

from flask import Flask, request
import json
import redis
import re

REGEX_PATTERN = re.compile(r'(?:sample#)?(\S*)=(\S*)')
REDIS_LIST_NAME = 'logs'

app = Flask(__name__)
redis_client = redis.StrictRedis(host='localhost', port=6379)


@app.route('/', methods=['POST'])
def process_post_request():
    # getting log received from POST request and building raw log file path
    raw_log = request.json['log']

    # parsing the raw log as we did in level_1 and level_2
    log_dict = {}
    for (key, value) in re.findall(REGEX_PATTERN, raw_log):
        log_dict[key] = value

    # putting the parsed log (json format) in the list
    # the use of lpush instead rpush is arbitrary
    # no pretty json formatting chosen on purpose
    redis_client.lpush(REDIS_LIST_NAME, json.dumps(log_dict))

    # return a 204 no content status
    return '', 204


if __name__ == "__main__":
    app.run(host='localhost', port=3000)
