# coding: utf8
import re
import pycparser.c_generator


PREFIXES = {
    None: 'CAIRO_SURFACE_OBSERVER_',
    '_cairo_status': 'CAIRO_STATUS_',
    '_cairo_path_data_type': 'CAIRO_PATH_',
    '_cairo_text_cluster_flags': 'CAIRO_TEXT_CLUSTER_FLAG_',
    '_cairo_ps_level': 'CAIRO_',
    '_cairo_pdf_version': 'CAIRO_',
    '_cairo_svg_version': 'CAIRO_',
}


class Visitor(pycparser.c_ast.NodeVisitor):
    def visit_Enum(self, node):
        prefix = PREFIXES.get(node.name)
        if prefix is None:
            assert node.name.startswith('_cairo_')
            prefix = node.name[1:].upper()
            if prefix.endswith('_t'):
                prefix = prefix[:-1]
            else:
                prefix += '_'
        for enumerator in node.values.enumerators:
            assert enumerator.name.startswith(prefix)
            new_name = enumerator.name[len(prefix):]
            print('%s = %r' % (enumerator.name[6:], new_name))
            enumerator.name = new_name
        print('')


def generate(include_dir):
    # Remove comments, preprocessor instructions and macros.
    source = re.sub(
        b'/\*.*?\*/'
        b'|CAIRO_(BEGIN|END)_DECLS'
        b'|cairo_public '
        br'|^\s*#.*?[^\\]\n',
        b'',
        b''.join(open('%s/cairo%s.h' % (include_dir, suffix), 'rb').read()
                 for suffix in ['', '-pdf', '-ps', '-svg']),
        flags=re.DOTALL | re.MULTILINE)
    print('# Generated by mkconstants.py\n')
    ast = pycparser.CParser().parse(source)
    Visitor().visit(ast)
    source = pycparser.c_generator.CGenerator().visit(ast)
    print('_CAIRO_HEADERS = r"""\n%s\n"""' % source.strip())


if __name__ == '__main__':
    generate('/usr/include/cairo')
