import warnings
warnings.warn(f"module {__name__!r} is deprecated",
              DeprecationWarning,
              stacklevel=2)

from re import _constants as _
globals().update({k: v for k, v in vars(_).items() if k[:2] != '__'})

if __name__ == "__main__":
    def dump(f, d, typ, int_t, prefix):
        items = sorted(d)
        f.write(f"""\
#[derive(num_enum::TryFromPrimitive, Debug)]
#[repr({int_t})]
#[allow(non_camel_case_types, clippy::upper_case_acronyms)]
pub enum {typ} {{
""")
        for item in items:
            name = str(item).removeprefix(prefix)
            val = int(item)
            f.write(f"    {name} = {val},\n")
        f.write("""\
}
""")
    import sys
    if len(sys.argv) > 1:
        constants_file = sys.argv[1]
    else:
        import os
        constants_file = os.path.join(os.path.dirname(__file__), "../../sre-engine/src/constants.rs")
    with open(constants_file, "w") as f:
        f.write("""\
/*
 * Secret Labs' Regular Expression Engine
 *
 * regular expression matching engine
 *
 * NOTE: This file is generated by sre_constants.py.  If you need
 * to change anything in here, edit sre_constants.py and run it.
 *
 * Copyright (c) 1997-2001 by Secret Labs AB.  All rights reserved.
 *
 * See the _sre.c file for information on usage and redistribution.
 */

""")

        f.write("use bitflags::bitflags;\n\n");

        f.write("pub const SRE_MAGIC: usize = %d;\n" % MAGIC)

        dump(f, OPCODES, "SreOpcode", "u32", "")
        dump(f, ATCODES, "SreAtCode", "u32", "AT_")
        dump(f, CHCODES, "SreCatCode", "u32", "CATEGORY_")

        def bitflags(typ, int_t, prefix, flags):
            f.write(f"""\
bitflags! {{
    pub struct {typ}: {int_t} {{
""")
            for name in flags:
                val = globals()[prefix + name]
                f.write(f"        const {name} = {val};\n")
            f.write("""\
    }
}
""")

        bitflags("SreFlag", "u16", "SRE_FLAG_", [
            "TEMPLATE",
            "IGNORECASE",
            "LOCALE",
            "MULTILINE",
            "DOTALL",
            "UNICODE",
            "VERBOSE",
            "DEBUG",
            "ASCII",
        ])

        bitflags("SreInfo", "u32", "SRE_INFO_", [
            "PREFIX", "LITERAL", "CHARSET",
        ])

    print("done")
