#!/usr/bin/python2
# -*- coding: utf-8 -*-
from __future__ import print_function

import io
import json
import os
import sys
from collections import defaultdict

RESULTS_MAPPING = {
    "SKIP": "SKIP",
    "PASS": "OK",
    "INFO": "INFO",
    "WARN": "VERIFY",
    "FAIL": "BAD",
    "ERROR": "BAD",
}

mtps_log_dir = sys.argv[1]

results = defaultdict(list)
for log_filename in os.listdir(mtps_log_dir):
    if not log_filename.endswith(".log"):
        continue
    log_path = os.path.join(mtps_log_dir, log_filename)
    if not os.path.isfile(log_path):
        continue

    # For example:
    # FAIL-045051-install-systemd-standalone-sysusers-0:252-2.el9.x86_64.log
    name_without_ext = log_filename[: -len(".log")]
    result, test_run_id, test_name, test_object = name_without_ext.split("-", 3)
    if result not in RESULTS_MAPPING:
        # This is probably some file we do not want to handle.
        continue

    # Selinux test has the "selinux" infix, for example:
    # WARN-selinux-045051-install-systemd-container-0:252-2.el9.x86_64.log
    if test_run_id == "selinux":
        result, _, _, test_name, test_object = name_without_ext.split("-", 4)
        test_object += " (SELinux AVCs)"

    # The mtps log file with mtps-get-task object contains information about
    # the download of Brew build, for example:
    # PASS-045029-49526253-mtps-get-task.log
    if test_object == "mtps-get-task":
        test_name = "download build"
        test_object = None

    if test_object == "mtps-get-module":
        test_name = "module info"
        test_object = None

    if test_object == "mtps-run-tests":
        test_name = "tests"
        test_object = None

    # dnf5 can print invalid UTF characters due to https://github.com/rpm-software-management/dnf5/issues/1865
    with io.open(log_path, "r", encoding="utf-8", errors="replace") as f:
        details = f.read()

    message = "{0}: {1}".format(test_name, test_object) if test_object else test_name
    results[test_name].append(
        {
            "result": RESULTS_MAPPING[result],
            "message": message,
            "details": details,
        }
    )

print(json.dumps(results, indent=2))
