#!/usr/bin/env python3

import json
import sys
import time

levels = {
    'error': '\033[91m',
    'warning': '\033[93m',
    'diff': '\033[95m',
    'key': '\033[97m',
    'info': '\033[0m',
}

cancel_colour = '\033[0m'

def col_wrap(stri, collev):
    return levels["key"] + stri + collev

filters = {sp[0]: sp[1] for sp in [arg.split(":", 1) for arg in sys.argv[1:]]}

def print_message(line):
    ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(js["ts"])))

    string = ""
    if 'level' in js:
        collev = levels[js['level']]
    elif js.get('diff') != None:
        collev = levels['diff']
    else:
        collev = cancel_colour

    string += collev

    app = "[%s]" % js["app"] if "app" in js else ""
    string += f'[{ts}] {js["level"].upper()} {js.get("ctrl", "").upper()} {app} {js["msg"]} '
    del(js['msg'])
    del(js['ts'])
    del(js['level'])
    if 'ctrl' in js:
        del(js['ctrl'])
    del(js['logger'])
    s_key = sorted(js.keys())
    string += " ".join([f"{col_wrap(k, collev)}:{js[k]}" for k in s_key])
    string += cancel_colour
    print(string)


for line in sys.stdin:
    try:
        js = json.loads(line)
    except:
        nline = line.strip("\n")
        string = levels['error']
        string += nline
        string += cancel_colour
        print(string)
        continue
    skip_flag = False
    for k, v in filters.items():
        if js.get(k) != v:
            skip_flag = True
    if not skip_flag:
        print_message(js)
    sys.stdout.flush()
