import os
import subprocess
import re

def run_command(command):
    try:
        subprocess.run(command, check=True, shell=True)
    except subprocess.CalledProcessError as e:
        print(f"An error occurred while running the command: {e}")
        exit(1)

def extract_content(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
    match = re.search(r'static const.*?};', content, re.DOTALL)
    if match:
        return match.group(0)
    else:
        print("No matching content found in the .c file.")
        exit(1)

def insert_content(template_path, content, position):
    with open(template_path, 'r') as file:
        lines = file.readlines()

    if position == "before_else":
        start_index = lines.index("#if GTK_CHECK_VERSION(3,20,0)\n") + 1
        end_index = lines.index("#else\n", start_index)
        lines[start_index:end_index] = [content + "\n"]
    elif position == "after_else":
        gtk_check_index = lines.index("#if GTK_CHECK_VERSION(3,20,0)\n")
        else_index = lines.index("#else\n", gtk_check_index)
        end_index = lines.index("#endif\n", else_index)
        lines[else_index + 1:end_index] = [content + "\n"]

    with open(template_path, 'w') as file:
        file.writelines(lines)

# Step 1: Run the first glib-compile-resources command
run_command("glib-compile-resources --target=.c --generate-source .gresource.xml --c-name resources")

# Step 2: Copy the template file
template_path = '.gresource_template.c'
copy_path = '.gresource_template_copy.c'
if not os.path.exists(template_path):
    print("Template file does not exist.")
    exit(1)
os.system(f'cp {template_path} {copy_path}')

# Step 3: Extract content from .c file and insert into the copied template
c_file_content = extract_content('.c')
insert_content(copy_path, c_file_content, "before_else")

# Step 4: Run the second glib-compile-resources command
run_command("glib-compile-resources --target=.c --generate-source .gresource_pre_gtk3_20.xml --c-name resources")

# Step 5: Extract new content from .c file and insert
new_c_file_content = extract_content('.c')
insert_content(copy_path, new_c_file_content, "after_else")

# Step 6: Move the copied template file to the parent directory
parent_directory = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
os.rename(copy_path, os.path.join(parent_directory, '.gresource.c'))
print(".gresource.c file has been successfully created and moved.")

# Step 7: Remove the .c file
c_file_path = '.c'
if os.path.exists(c_file_path):
    os.remove(c_file_path)
    print(".c file has been removed.")
else:
    print(".c file not found or already removed.")
