import re, sys
from distutils import sysconfig, util
from distutils.errors import DistutilsPlatformError

# a modified version of distutils.sysconfig.parse_config_h that supports
# defines with lowercase letters (need for Py_* defines)
def _parse_config_h(fn, g=None):
    """Parse a config.h-style file.

    A dictionary containing name/value pairs is returned.  If an
    optional dictionary is passed in as the second argument, it is
    used instead of a new dictionary.
    """
    fp = open(fn, 'r')

    if g is None:
        g = {}

    define_rx = re.compile("#define ([a-zA-Z][a-zA-Z0-9_]+) (.*)\n")
    undef_rx = re.compile("/[*] #undef ([a-zA-Z][a-zA-Z0-9_]+) [*]/\n")

    while True:
        line = fp.readline()
        if not line:
            break
        m = define_rx.match(line)
        if m:
            n, v = m.group(1, 2)
            try: v = int(v)
            except ValueError: pass
            g[n] = v
        else:
            m = undef_rx.match(line)
            if m:
                g[m.group(1)] = 0

    fp.close()
    
    return g

_defines = None
def _init_platform():
    g = {}
    try:
        filename = sysconfig.get_config_h_filename()
        _parse_config_h(filename, g)
    except IOError, msg:
        my_msg = "invalid Python installation: unable to open %s" % filename
        if hasattr(msg, "strerror"):
            my_msg = my_msg + " (%s)" % msg.strerror

        raise DistutilsPlatformError(my_msg)

    global _defines
    _defines = g
    
def get_defines(*args):
    """
    With no arguments, return a dictionary of all defines configured for
    the current build.

    With arguments, return a list of values that result from looking up
    each argument in the configuration variable dictionary.
    """
    global _defines
    if _defines is None:
        _init_platform()
    
    if args:
        vals = []
        for name in args:
            vals.append(_defines.get(name))
        return vals
    else:
        return _defines

def get_define(name):
    """
    Return the value of a single define using the dictionary returned
    by 'get_defines()'.  Equivalent to get_defines().get(name)
    """
    return get_defines().get(name)

def GetPlatformSpecifier():
    specifier = '%s-%s' % (util.get_platform(), sys.version[0:3])
    if get_define('Py_DEBUG'):
        specifier += '-debug'
    return specifier
    
