import re, sys, os
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

def GetDocOptions():
    # ick, we cannot use 'self.distribution.developer_mode' because help is
    # displayed without instantiating the class!
    with_docs_help = 'enable documentation build'
    without_docs_help = 'disable documentation build'
    if os.path.exists('PKG-INFO'):
        # source dist, --with-docs default
        with_docs_help += ' [default]'
    else:
        # CVS variety, --without-docs default
        without_docs_help += ' [default]'

    return [('with-docs', None, with_docs_help),
            ('without-docs', None, without_docs_help),
            ]
