import os
import xml.etree.ElementTree as ET

def prettify(element, indent='    '):
    """Add indentation and line breaks to make the XML file human-readable."""
    def set_indent(elem, level=0):
        i = "\n" + level * indent
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + indent
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                set_indent(elem, level+1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

    set_indent(element)

def create_gresource_xml(file_name, include_pre_gtk3_20):
    po_dir = "../po"  # Directory containing .po files

    # Read base names from .po files and add 'en', then sort
    base_names = sorted([os.path.splitext(po_file)[0] for po_file in os.listdir(po_dir) if po_file.endswith('.po')] + ['en_US'])

    root = ET.Element('gresources')
    gresource = ET.SubElement(root, 'gresource', prefix="/org/kickshaw/")
    
    initial_files = ["imgs/logo_about_1.jpg", "imgs/logo_about_2.png", "imgs/logo_about_3.jpg", "imgs/logo_about_4.png", "txts/credits"]
    for f in initial_files:
        ET.SubElement(gresource, 'file', compressed="true").text = f

    def add_file_entries(pattern):
        for basename in base_names:
            file_path = pattern.format(basename=basename)
            ET.SubElement(gresource, 'file', compressed="true").text = file_path

    add_file_entries("txts/hints/{basename}/hints1_{basename}")
    if include_pre_gtk3_20:
        add_file_entries("txts/hints/{basename}/hints2_pre_gtk3_20_{basename}")
    else:
        add_file_entries("txts/hints/{basename}/hints2_{basename}")
    add_file_entries("txts/hints/{basename}/hints3_{basename}")

    info_patterns = ["txts/info/{basename}/info_version_{basename}", "txts/info/{basename}/info_hints_{basename}",
                     "txts/info/{basename}/info_arguments_{basename}", "txts/list_of_shortcuts/{basename}"]
    for pattern in info_patterns:
        add_file_entries(pattern)

    for i in range(1, 36):
        ET.SubElement(gresource, 'file', compressed="true").text = f"txts/quotes/quote{i}"

    final_files = ["txts/quotes/quote35_kickshaw_forks", "txts/quotes/quote35_cities",
                   "txts/quotes/quote35_objects", "txts/quotes/quote35_locations"]
    for f in final_files:
        ET.SubElement(gresource, 'file', compressed="true").text = f

    prettify(root)
    tree = ET.ElementTree(root)
    with open(file_name, "wb") as f:
        tree.write(f, encoding="utf-8", xml_declaration=True)

# Create both versions of the file
create_gresource_xml(".gresource.xml", False)
create_gresource_xml(".gresource_pre_gtk3_20.xml", True)
