#!/usr/bin/env python

"""Create the macros needed to compile the Sherpa XSPEC module.

The models definitions change over time - normally adding new ones but
sometimes changing the symbol name for the same model - and this is
handled by defining a symbol XSPEC_x_y_z for each supported XSPEC
version x.y.z (the patch level is assumed to not be relevant here).

"""

import re
import sys

# Local import (this is also copied to sherpa.astro.utils.xspec so it
# can be used by Sherpa, but this code has to be usable without a
# Sherpa installation).
import xspec


def make_macros(version: str) -> list[str]:
    """Convert the given XSPEC version into a set of arguments."""

    xspec_version = xspec.get_version(version)

    if xspec_version < xspec.MIN_VERSION:
        raise ValueError(f"XSPEC Version {xspec_version} is less "
                         f"than {xspec.MIN_VERSION}, which is the "
                         "earliest supported version for Sherpa")

    # How best to warn the user (and is this the best place to do this?)
    #
    if xspec_version > xspec.MAX_VERSION:
        sys.stderr.write("WARNING: XSPEC Version is greater than "
                         f"{xspec.MAX_VERSION}, which is the latest "
                         "supported version for Sherpa\n")

    out = []
    for version in xspec.SUPPORTED_VERSIONS:
        if xspec_version >= version:
            major, minor, micro = version
            out.append(f"-DXSPEC_{major}_{minor}_{micro}")

    if len(out) == 0:
        raise RuntimeError(f"Unable to process XSPEC version '{version}'")

    return out


if __name__ == "__main__":

    if len(sys.argv) != 2:
        sys.stderr.write(f"Usage: {sys.argv[0]} version\n")
        sys.exit(1)

    opts = make_macros(sys.argv[1])
    print(" ".join(opts))
