import os
import re

def generate_c_array(directory_path):
    # Get the list of .po files in the specified directory
    po_files = [f for f in os.listdir(directory_path) if f.endswith('.po')]

    # Extract base names from file names
    base_names = [os.path.splitext(file)[0] for file in po_files]

    # Sort the base names
    sorted_base_names = sorted(base_names)

    # Format the array string
    array_str = 'gchar *provided_locales[] = { '
    line = ''
    for i, name in enumerate(sorted_base_names):
        line += '"' + name + '"'
        if i != len(sorted_base_names) - 1:  # Add comma except for the last element
            line += ', '
        if (i + 1) % 10 == 0 or i == len(sorted_base_names) - 1:
            array_str += line
            if i != len(sorted_base_names) - 1:
                array_str += '\n' + ' ' * 34
            line = ''
    
    array_str += ' };'
    return array_str

def update_c_source_file(c_file_path, new_array_str):
    # Read the content of the C source file
    with open(c_file_path, 'r') as file:
        content = file.read()

    # Define a regular expression pattern to find the existing array
    pattern = r'gchar \*provided_locales\[\] = \{[^}]*\};'

    # Replace the old array with the new one
    updated_content = re.sub(pattern, new_array_str, content, flags=re.DOTALL)

    # Write the updated content back to the file
    with open(c_file_path, 'w') as file:
        file.write(updated_content)

# Paths
directory_path = '../po'
c_file_path = '../kickshaw.c'

# Generate the C-style character array
c_array = generate_c_array(directory_path)

# Update the .c source file
update_c_source_file(c_file_path, c_array)

