import json
import argparse
import sys

def generate_event_h(input_json_path, output_h_path):
    """
    Generate a .h file with enum definitions for eventCode and functionCode from a JSON file.

    Args:
        input_json_path (str): Path to the input JSON file.
        output_h_path (str): Path to the output .h file.
    """
    # Read the JSON file with Python 2.x and 3.x compatibility
    if sys.version_info[0] < 3:
        # Python 2.x
        with open(input_json_path, "r") as json_file:
            data = json.load(json_file)
    else:
        # Python 3.x
        with open(input_json_path, "r", encoding="utf-8") as json_file:
            data = json.load(json_file)

    # Extract unique event codes and function codes
    event_codes = set()
    function_codes = set()

    for event in data["event_tmplate"]:
        # Replace hyphens with underscores in eventInfo
        event_info = event["eventInfo"].replace("-", "_").replace(" ", "_")
        event_codes.add((event["eventCode"], event_info))
        function_codes.add(event["functionCode"])

    # Generate the .h file content
    header_content = """#ifndef EVENT_CODES_H
#define EVENT_CODES_H

// EventCode Enum
typedef enum {
"""

    # Add event codes to the header
    for code, desc in sorted(event_codes, key=lambda x: x[0]):
        header_content += "    EVENT_{0} = {1},\n".format(desc.upper(), code)

    header_content += """} EventCode;

// FunctionCode Enum
typedef enum {
"""

    # Add function codes to the header
    for code in sorted(function_codes):
        header_content += "    FUNCTIONCODE_{0} = {1},\n".format(code, code)

    header_content += """} FunctionCode;

#endif // EVENT_CODES_H
"""

    # Write the content to the .h file
    if sys.version_info[0] < 3:
        # Python 2.x
        with open(output_h_path, "w") as h_file:
            h_file.write(header_content.encode("utf-8"))
    else:
        # Python 3.x
        with open(output_h_path, "w", encoding="utf-8") as h_file:
            h_file.write(header_content)

    print("Header file '{0}' has been generated.".format(output_h_path))

if __name__ == "__main__":
    # Set up argument parser
    parser = argparse.ArgumentParser(description="Generate a .h file with enum definitions for eventCode and functionCode from a JSON file.")
    parser.add_argument("--input", type=str, required=True, help="Path to the input JSON file.")
    parser.add_argument("--output", type=str, required=True, help="Path to the output .h file.")
    
    # Parse arguments
    args = parser.parse_args()
    
    # Generate the .h file
    generate_event_h(args.input, args.output)