#!/usr/bin/env python3
"""Show how this DFTracer was configured and built.

Generated by CMake at configure time. Values and paths are baked in, and only
the Python standard library is used: nothing is imported from dftracer and no
MPI/HDF5/PAPI runtime has to be loaded.

Usage: dftracer_install_info [--json]
"""
import json
import re
import sys
import textwrap

L = lambda s: [x for x in s.split(";") if x]
B = lambda v: bool(v)

# Nothing below is a hand-kept version table. CMake (DFTracerBuildInfo.cmake)
# read every list from the sources this build compiled and the brahma headers
# it compiled against:
#   MPI   compat families = brahma interface/<kind>_*_compat.h that also have a
#         tracer in core/brahma/<kind>_*_compat.cpp
#   HDF5  the BRAHMA_HDF5_VERSION ranges guarding core/brahma/hdf5.cpp
#   CUDA  the CUPTI struct bands and verified-headers list in
#         core/function/cuda/intercept.cpp
#   ROCm  the rocprofiler-sdk API gates in core/function/hip/
MPI_FAMILIES = L("")
MPIIO_FAMILIES = L("")
MPI_BRAHMA_ONLY = L("") + \
    ["mpiio " + s for s in L("")]
MPI_TRACER_ONLY = L("craympich_8_1;craympich_9_0;craympich_9_1;mpich_3_4;mpich_4_2;mvapich_2_3;openmpi_4_1;openmpi_5_0") + \
    ["mpiio " + s for s in L("craympich_9_0;craympich_9_1;mpich_4_2")]
GENERATED_FROM = L("")
HDF5_GATES = [tuple(int(x) for x in r.split(":")) for r in L("100823:100900;101005:101100;101203:101300;101405:101500;101011:101100")]
CUDA_BANDS = L("13.0;12.9;12.6;12.0;11.8;11.6;11.2;11.0;11.7")
CUDA_VERIFIED = "10.1, 10.2, 11.1-11.8, 12.2, 12.6, 12.9 and 13.1"
ROCM_GATES = L("0.5.0;0.6.0;1.0.0")

# Display names only; an implementation missing here prints as brahma names it.
_IMPL_NAMES = {"openmpi": "OpenMPI", "mpich": "MPICH", "mvapich": "MVAPICH2",
               "craympich": "Cray MPICH", "intelmpi": "Intel MPI"}


def impl_name(impl):
    return _IMPL_NAMES.get(impl, impl)


def family_name(slug):
    impl, major, minor = slug.rsplit("_", 2)
    return "%s %s.%s.x" % (impl_name(impl), major, minor)


def ver(n):  # brahma encodes major*100000 + minor*100 + patch
    return "%d.%d.%d" % (n // 100000, (n // 100) % 1000, n % 100) if n else ""


def merge(rs):
    """Union of [lo, hi) ranges, sorted."""
    out = []
    for a, b in sorted(rs):
        if out and a <= out[-1][1]:
            out[-1] = (out[-1][0], max(out[-1][1], b))
        else:
            out.append((a, b))
    return out


def fmt_range(a, b):
    lo, hi = ver(a), ver(b - 1)
    # [1.14.5, 1.15.0) reads as 1.14.5-1.14.x
    if b % 100 == 0 and (a // 100) == ((b - 1) // 100):
        return "%s-%s.x" % (lo, hi.rsplit(".", 1)[0])
    return "%s-%s" % (lo, hi)


def fmt_ranges(rs):
    return ", ".join(fmt_range(a, b) for a, b in rs)


def in_ranges(n, rs):
    return any(a <= n < b for a, b in rs)


def vtuple(v):
    return tuple(int(x) for x in v.split(".") if x.isdigit())


HDF5_RANGES = merge(HDF5_GATES)
_cuda_vs = sorted({vtuple(v) for v in re.findall(r"\d+\.\d+", CUDA_VERIFIED)} |
                  {vtuple(b) for b in CUDA_BANDS})
CUDA_MIN = min((vtuple(v) for v in re.findall(r"\d+\.\d+", CUDA_VERIFIED)), default=None)
CUDA_MAX_MAJOR = _cuda_vs[-1][0] if _cuda_vs else None

COMPAT_TEXT = ", ".join(family_name(f) for f in MPI_FAMILIES) or "no implementation"
GENERATED_TEXT = ", ".join(
    "%s %s" % (impl_name(g.split()[0]), g.split()[1]) for g in GENERATED_FROM)

SUPPORTED = {
    "mpi": "any MPI implementation and version traces the common MPI and "
           "MPI-IO calls. Calls beyond the common set are traced for " + COMPAT_TEXT
           + (" (generated from " + GENERATED_TEXT + ")" if GENERATED_TEXT else "")
           + ".",
    "hdf5": (fmt_ranges(HDF5_RANGES) + ". Other versions build but trace no HDF5 calls.")
            if HDF5_RANGES else "no HDF5 wrappers found in core/brahma/hdf5.cpp.",
    "cuda": ("CUDA %d.%d through %d.x" % (CUDA_MIN + (CUDA_MAX_MAJOR,))
             + (" (headers checked: %s)" % CUDA_VERIFIED if CUDA_VERIFIED else "")
             + ". CUPTI record structs are chosen from the toolkit version"
             + (", with bands starting at " + ", ".join(sorted(CUDA_BANDS, key=vtuple))
                if CUDA_BANDS else "") + ".")
            if CUDA_MIN and CUDA_MAX_MAJOR else "no CUPTI version bands found.",
    "rocm": "rocprofiler-sdk, shipped with ROCm 6.2.0 and later; older ROCm "
            "has no rocprofiler-sdk."
            + (" Code paths branch at API " + ", ".join(ROCM_GATES) + "."
               if ROCM_GATES else ""),
    "papi": "any PAPI that provides the preset events; no version gate.",
    "variorum": "any Variorum; no version gate.",
    "hwloc": "any hwloc; no version gate.",
}


def cuda_status(v):
    try:
        t = vtuple(v)[:2]
    except ValueError:
        return "unknown"
    if not (CUDA_MIN and CUDA_MAX_MAJOR):
        return "unknown"
    return "supported" if (t >= CUDA_MIN and t[0] <= CUDA_MAX_MAJOR) else \
        "outside the verified range (CUPTI struct selection may be wrong)"


mpi_on, hdf5_on = B(False), B(False)
mpi_n, hdf5_n = int("0"), int("0")
# The compat family brahma compiles in for this MPI (implementation, major,
# minor), as CMake computed it from brahma_config.hpp.
mpi_slug = ""
ev = L("CYCLE:PAPI_TOT_CYC;INSTRUCTION:PAPI_TOT_INS".replace(",", ";"))
fit = int("0" or 0)

INFO = {
    "version": "2.0.3",
    "install_prefix": "/project/build/lib.linux-x86_64-cpython-310/dftracer",
    "features": {
        # name: [requested at configure time, enabled in the build]
        "mpi": [False, False],
        "hdf5": [False, False],
        "function_tracing": [False, False],
        "hip_tracing": [False, False],
        "cuda_tracing": [False, False],
        "papi_tracing": [False, False],
        "variorum_power": [False, False],
        "hwloc": [False, False],
        "dynamic_detection": [False, False],
    },
    "mpi": {
        "implementation": "UNKNOWN",
        "version": "",
        "c_compiler": "",
        "cxx_compiler": "",
        "include_dirs": L(""),
        "libraries": L(""),
        "brahma_implementation": "",
        "brahma_enabled": False,
        "brahma_version_number": mpi_n,
        "common_calls_traced": mpi_on and False,
        "compat_interface": mpi_slug if mpi_slug in MPI_FAMILIES else "",
        "mpiio_compat_interface": mpi_slug if mpi_slug in MPIIO_FAMILIES else "",
        "compat_interfaces_available": MPI_FAMILIES,
        "mpiio_compat_interfaces_available": MPIIO_FAMILIES,
        # brahma ships these but DFTracer has no tracer: rerun
        # tools/generate_interfaces_from_brahma.py against this brahma.
        "compat_brahma_only": MPI_BRAHMA_ONLY,
        # DFTracer has a tracer but this brahma has no interface for it.
        "compat_tracer_only": MPI_TRACER_ONLY,
        "generated_from": GENERATED_FROM,
    },
    "hdf5": {
        "version": "",
        "include_dirs": L(""),
        "libraries": L(""),
        "brahma_enabled": False,
        "brahma_version_number": hdf5_n,
        "supported_ranges": fmt_ranges(HDF5_RANGES),
        "calls_traced": hdf5_on and False and in_ranges(hdf5_n, HDF5_RANGES),
    },
    "papi": {
        "include_dirs": L(""),
        "libraries": L(""),
        "detected_events": "CYCLE:PAPI_TOT_CYC;INSTRUCTION:PAPI_TOT_INS",
        "detected_count": len(ev),
        "hw_counters": int("0" or 0),
        "fitting_counters": fit,
        "multiplexed": 0 < fit < len(ev),
    },
    "gpu": {
        "rocprofiler_sdk_version": "",
        "rocprofiler_sdk_include": "",
        "cuda_version": "",
        "cupti_include": "",
        "cuda_status": "",
    },
    "supported_versions": SUPPORTED,
    "variorum": {
        "include_dirs": L(""),
        "libraries": L(""),
    },
    "hwloc": {
        "include_dirs": L(""),
        "libraries": L(""),
    },
    "brahma": {
        "dir": "/opt/dftracer-deps/lib64/cmake/brahma",
        "include_dirs": L("/opt/dftracer-deps/include"),
    },
    "producer_consumer_ring": {
        "blocks": int("" or 0),
        "block_size": int("" or 0),
    },
    "toolchain": {
        "build_type": "Release",
        "cmake": "4.4.4",
        "c_compiler": "/opt/rh/gcc-toolset-14/root/usr/bin/cc",
        "c_compiler_id": "GNU 14.2.1",
        "cxx_compiler": "/opt/rh/gcc-toolset-14/root/usr/bin/c++",
        "cxx_compiler_id": "GNU 14.2.1",
        "libc": "",
    },
}

if INFO["gpu"]["cuda_version"]:
    INFO["gpu"]["cuda_status"] = cuda_status(INFO["gpu"]["cuda_version"])

OK, NO = "✔", "✘"


def row(k, v):
    if isinstance(v, list):
        v = ", ".join(v)
    return "  %-22s: %s" % (k, v if v not in ("", None) else "-")


def pretty(i):
    out = ["DFTracer %s  (prefix %s)" % (i["version"], i["install_prefix"]), "",
           "Features   (requested -> enabled)"]
    for k, (req, on) in i["features"].items():
        warn = "   <-- requested but NOT enabled" if req and not on else ""
        out.append("  %s %-18s %s%s" % (OK if on else NO, k, "ON" if on else "off", warn))
    m = i["mpi"]
    out += ["", "MPI"]
    out += [row(k, v) for k, v in m.items()
            if k not in ("common_calls_traced", "compat_interface", "mpiio_compat_interface",
                         "compat_interfaces_available", "mpiio_compat_interfaces_available",
                         "compat_brahma_only", "compat_tracer_only", "generated_from")]
    on = i["features"]["mpi"][1]
    out.append("  %-22s: %s" % ("common calls traced", OK if m["common_calls_traced"] else NO))
    if on:
        out.append(row("compat calls traced", m["compat_interface"] or
                       "none (no compat interface for this MPI; common calls only)"))
        out.append(row("MPI-IO compat calls", m["mpiio_compat_interface"] or "none"))
    out.append(row("compat interfaces for", ", ".join(family_name(f) for f in m["compat_interfaces_available"])))
    out.append(row("MPI-IO compat for", ", ".join(family_name(f) for f in m["mpiio_compat_interfaces_available"])))
    out.append(row("generated from", ", ".join(m["generated_from"])))
    if m["compat_brahma_only"]:
        out.append(row("brahma-only (untraced)", m["compat_brahma_only"])
                   + "   <-- regenerate DFTracer's compat tracers")
    if m["compat_tracer_only"]:
        out.append(row("tracer-only (unused)", m["compat_tracer_only"]))
    h = i["hdf5"]
    out += ["", "HDF5"]
    out += [row(k, v) for k, v in h.items() if k not in ("calls_traced", "supported_ranges")]
    out.append(row("supported versions", h["supported_ranges"]))
    out.append("  %-22s: %s%s" % ("calls traced", OK if h["calls_traced"] else NO,
        "" if h["calls_traced"] or not i["features"]["hdf5"][1] else
        "   (version outside supported ranges: wrappers compiled out)"))
    out += ["", "Supported versions"]
    for k, v in i["supported_versions"].items():
        out.append(textwrap.fill(v, 78, initial_indent="  %-9s " % k,
                                 subsequent_indent=" " * 12))
    for sec, title in (("papi", "PAPI"), ("gpu", "GPU"), ("variorum", "Variorum"),
                       ("hwloc", "hwloc"), ("brahma", "brahma"),
                       ("producer_consumer_ring", "Producer/consumer ring"),
                       ("toolchain", "Toolchain")):
        out += ["", title] + [row(k, v) for k, v in i[sec].items()]
    return "\n".join(out)


def main(argv):
    if "-h" in argv or "--help" in argv:
        print(__doc__.strip())
        return 0
    print(json.dumps(INFO, indent=2) if "--json" in argv else pretty(INFO))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
