#! /usr/bin/python3

"""
The csdiff tool doesn't support the Ruff's JSON output yet.  So this just a
trivial wrapper which reads Ruff's report and transforms it to JSON which is
supported by csdiff.

The script accepts the same parameters as `ruff check` itself.
"""

import os
import sys
import json
from subprocess import Popen, PIPE


def ruff_check():
    """
    Run `ruff check` and return a dict with its results
    """
    cmd = ["ruff", "check", "--output-format=json"] + sys.argv[1:]
    with Popen(cmd, stdout=PIPE) as proc:
        out, _err = proc.communicate(timeout=60)
    return json.loads(out)


def ruff_code_to_name():
    """
    Introspect ruff and map all possible noqa codes to a human-readable names.
    """
    cmd = ["ruff", "rule", "--all", "--output-format=json"]
    with Popen(cmd, stdout=PIPE) as proc:
        out, _err = proc.communicate(timeout=60)
    return {i["code"]: i["name"] for i in json.loads(out)}


def main():
    """
    The main fuction
    """
    defects = ruff_check()
    code_to_name_map = ruff_code_to_name()

    for defect in defects:
        path = os.path.relpath(defect["filename"])
        column = defect["location"]["column"] or ""
        colsep = ":" if column else ""
        try:
            event = f"{defect['code']}[{code_to_name_map[defect['code']]}]"
        except KeyError:
            # Ruff is using weird "code" :-/
            event = f"RUFF_UNKNOWN_ERROR[{defect['code']}]"

        print("Error: RUFF_WARNING:")
        print("{file}:{line}{colsep}{column}: {event}: {msg}".format(
            file=path,
            line=defect["location"]["row"],
            colsep=colsep,
            column=column,
            event=event,
            msg=defect["message"],
        ))
        print()


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