#!/usr/bin/env python
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
# NOTE: This code loads the `constants.py` from libclusterfuzz, then iterates
# over the entities in the module.  As is, this is slightly fragile.
#
# As such, this should be a manual effort where we check in the results, that
# way we can make adjustments as needed.


import string
import constants

data = {}

NAME_CHECK = string.ascii_uppercase + "_"

HEADER = """
// Rust generated by Microsoft, code originally from:
//      https://github.com/google/clusterfuzz/blob/master/src/
//          python/lib/clusterfuzz/stacktraces/constants.py
//
// Original Copyright:
//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

"""


for name in dir(constants):
    if all(x in NAME_CHECK for x in name):
        entry = getattr(constants, name)
        if entry is None:
            continue

        data[name] = entry

for_rust = {
    # since we always assume symbolication, combine these
    "STACK_FRAME_IGNORE_REGEXES": (
        [f'r"{x}"' for x in data["STACK_FRAME_IGNORE_REGEXES"]]
        + [f'r"{x}"' for x in data["STACK_FRAME_IGNORE_REGEXES_IF_SYMBOLIZED"]]
    ),
}

with open("../src/generated.rs", "w") as handle:
    handle.write(HEADER)
    for key in sorted(for_rust.keys()):
        if isinstance(for_rust[key], list):
            value = ",".join(for_rust[key])
            handle.write(f"pub const {key}: &[&str] = &[{value}];")
        elif isinstance(for_rust[key], str):
            value = for_rust[key]
            handle.write(f"pub const {key}: &str = {value};")
        else:
            raise Exception("unsupported for_rust type")
