"""Compare selected category:ID pairs against two pinned IBM AssetOpsBench profiles."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import re

REVISION = "e844f6468c6c68b328022e7ca8e31da140842cc7"
DIGESTS = {
    "mini": "7b6167310e504abbd52d040eba88306b6bdfe470c406021c74fed015a06debde",
    "lite": "edc6ba443f5f07532bd89a6a398c845689e19c7738d7f4194a4928c81594f1ca",
}


def read_profile(name):
    data = Path(name + ".yaml").read_bytes()
    if sha256(data).hexdigest() != DIGESTS[name]:
        raise ValueError(f"{name}.yaml differs from the pinned IBM file")
    # These two verified files use only named groups and integer list items.
    groups = {}
    for line in data.decode("ascii").splitlines():
        header = re.fullmatch(r"([a-z]+):(?: \[\])?", line)
        if header:
            group = header[1]
            groups[group] = set()
        else:
            groups[group].add(int(line.strip().removeprefix("- ")))
    return groups


parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path, help="new JSON report filename")
parser.add_argument("target", nargs="+", help="one or more category:ID pairs")
args = parser.parse_args()
try:
    profiles = {name: read_profile(name) for name in DIGESTS}
    mini, lite = profiles["mini"], profiles["lite"]
    checks = {}
    for target in args.target:
        pair = re.fullmatch(r"([a-z]+):([1-9][0-9]*)", target)
        if not pair or pair[1] not in mini or pair[1] not in lite:
            raise ValueError(f"unknown category or invalid category:ID pair: {target}")
        checks[target] = [name for name, groups in profiles.items() if int(pair[2]) in groups[pair[1]]]
    differences = {}
    for group in sorted({target.split(":")[0] for target in checks}):
        differences[group] = {"mini_only": sorted(mini[group] - lite[group]),
                              "both": sorted(mini[group] & lite[group]),
                              "lite_only": sorted(lite[group] - mini[group])}
    fits = [name for name in profiles if all(name in choices for choices in checks.values())]
    report = {"revision": REVISION, "profile_sha256": DIGESTS, "targets": checks,
              "one_profile_covers_all": fits, "group_differences": differences}
    with args.output.open("x", encoding="utf-8") as out:
        json.dump(report, out, indent=2)
        out.write("\n")
    print("One profile covers all:", ", ".join(fits) or "neither")
except (OSError, ValueError) as error:
    parser.exit(1, f"{error}\n")
