#!/usr/bin/env python3
"""Consistency check of BNC's structured logfile (option logFileStructured)

    logcheck.py CLASSIC_LOG JSON_LOG [LOGFMT_LOG]

Checks that every line of the JSON file is a JSON object and every line of the
logfmt file a sequence of key=value pairs, that both carry the same records,
that the records have the mandatory keys in the documented order (optional
'epoch' after 'time', GPS Time without 'Z'), that the records belong line by
line to the classic logfile ('msg' is the classic text without the "<mp>: "
prefix and trailing blanks, shortened for events whose fields carry the details, see matches();
classic lines without their "yy-mm-dd hh:mm:ss " prefix; the start line is
skipped, it goes to the file of the current date) and that 'time' (UTC) is the
GPS Time stamp of the classic line minus the GPS-UTC leap seconds. Prints a
summary of the records per level, component and event; exit code 1 on any
error.
"""

import collections
import datetime
import json
import re
import sys

HEAD = ["time", "level", "component", "event"]
LEVELS = {"info", "warning", "error"}
LEAP_GPS_UTC = 18          # valid since 2017-01-01


def parse_logfmt(line):
    rec, i, n = {}, 0, len(line)
    while i < n:
        j = line.index("=", i)
        key = line[i:j]
        i = j + 1
        if i < n and line[i] == '"':
            i += 1
            val = []
            while line[i] != '"':
                if line[i] == "\\":
                    i += 1
                    val.append({"n": "\n", "r": "\r", "t": "\t"}.get(line[i], line[i]))
                    if line[i] == "u":
                        val[-1] = chr(int(line[i + 1:i + 5], 16))
                        i += 4
                else:
                    val.append(line[i])
                i += 1
            i += 1
            rec[key] = "".join(val)
        else:
            j = line.find(" ", i)
            j = n if j < 0 else j
            raw = line[i:j]
            i = j
            if raw in ("true", "false"):
                rec[key] = raw == "true"
            elif raw == "null":
                rec[key] = None
            elif re.fullmatch(r"-?\d+", raw):
                rec[key] = int(raw)
            elif re.fullmatch(r"-?\d+\.\d*", raw):
                rec[key] = float(raw)
            else:
                rec[key] = raw
        if i < n:
            if line[i] != " ":
                raise ValueError("blank expected at %d" % i)
            i += 1
    return rec


# events with a short structured 'msg': prefix the classic line must start with
SHORT = {
    "ppp_position": lambda r: "%s %s X = " % (r["epoch"].replace("T", "_"), r["mp"]),
    "stream_latency": lambda r: "%s %s: Mean latency " % (r["mp"], r["type"]),
}

SHORT_MSG = {"ppp_position": "PPP position", "stream_latency": "Latency"}


def matches(r, line):
    """Does the record belong to the classic logfile line? The structured 'msg'
    is the classic text without the "<mp>: " prefix, shortened where the
    fields carry the details."""
    mp, msg, ev = r.get("mp"), r.get("msg"), r.get("event")
    if ev in SHORT:
        return msg == SHORT_MSG[ev] and line.startswith(SHORT[ev](r))
    if ev == "stream_content" and msg == "Received RTCM message":
        size = " (size %d)" % r["size"] if "size" in r else " "
        return line == "%s: Received message type %d%s" % (mp, r["message_type"], size)
    if mp and line.startswith(mp + ": "):
        line = line[len(mp) + 2:]
    line = line.rstrip(" ")
    if ev.startswith("stream_outage_") or ev.startswith("stream_corrupted_"):
        return line.startswith(msg + " ")
    return msg == line


def main():
    errors = []
    classic, stamps = [], []
    for line in open(sys.argv[1], encoding="latin-1", newline="").read().split("\r\n"):
        if not line or "========== Start BNC" in line:
            continue
        if re.match(r"\d\d-\d\d-\d\d \d\d:\d\d:\d\d ", line):
            classic.append(line[18:])
            stamps.append(datetime.datetime.strptime(line[:17], "%y-%m-%d %H:%M:%S"))
        else:
            classic.append(line)
            stamps.append(None)

    recs = []
    for k, line in enumerate(open(sys.argv[2], encoding="utf-8"), 1):
        try:
            recs.append(json.loads(line, object_pairs_hook=collections.OrderedDict))
        except ValueError as e:
            errors.append("json line %d: %s" % (k, e))
    if len(sys.argv) > 3:
        lf = []
        for k, line in enumerate(open(sys.argv[3], encoding="utf-8"), 1):
            try:
                lf.append(parse_logfmt(line.rstrip("\n")))
            except (ValueError, IndexError) as e:
                errors.append("logfmt line %d: %s" % (k, e))
        if len(lf) != len(recs):
            errors.append("json %d records, logfmt %d" % (len(recs), len(lf)))
        for k, (a, b) in enumerate(zip(recs, lf), 1):
            # the start line carries the wall clock time of each run
            start = "========== Start BNC" in a.get("msg", "")
            if list(a.keys()) != list(b.keys()) or any(a[x] != b[x] for x in a
                                                        if not (start and x == "time")):
                errors.append("record %d differs between json and logfmt" % k)

    count = collections.Counter()
    for k, r in enumerate(recs, 1):
        keys = list(r.keys())
        if keys[1:2] == ["epoch"]:
            try:
                datetime.datetime.strptime(r["epoch"], "%Y-%m-%dT%H:%M:%S.%f")
            except ValueError:
                errors.append("record %d: epoch %s" % (k, r["epoch"]))
            keys = keys[:1] + keys[2:]
        if keys[:4] != HEAD or keys[-2:] != ["msg", "v"]:
            errors.append("record %d: keys %s" % (k, keys))
            continue
        if r["level"] not in LEVELS:
            errors.append("record %d: level %s" % (k, r["level"]))
        count[(r["level"], r["component"], r["event"])] += 1

    body = [r for r in recs if "========== Start BNC" not in r.get("msg", "")]
    for k, (r, st) in enumerate(zip(body, stamps), 1):
        utc = datetime.datetime.strptime(r["time"], "%Y-%m-%dT%H:%M:%S.%fZ")
        if st is not None and (st - utc.replace(microsecond=0)).total_seconds() != LEAP_GPS_UTC:
            errors.append("record %d: time %s, classic %s" % (k, r["time"], st))
    for k, (r, line) in enumerate(zip(body, classic), 1):
        if not matches(r, line):
            errors.append("record %d: msg %r, classic %r" % (k, r.get("msg"), line))
            break
    if len(body) != len(classic):
        errors.append("%d records, %d classic lines" % (len(body), len(classic)))

    print("%d records" % len(recs))
    for (lev, comp, ev), n in sorted(count.items()):
        print("%6d %-8s %-8s %s" % (n, lev, comp, ev))
    for e in errors:
        print("ERROR", e)
    print("OK" if not errors else "%d error(s)" % len(errors))
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main())
