import os
import xml.etree.ElementTree as ET

def prettify(element, indent='    '):
    """Add indentation and line breaks to make the XML file human-readable."""
    queue = [(0, element)]  # (level, element)
    while queue:
        level, element = queue.pop(0)
        children = list(element)
        if children:
            element.text = '\n' + indent * (level+1)  # for child open
        if level and not element.tail:
            element.tail = '\n' + indent * level  # for close of this and parent tag
        for child in children:
            queue.append((level + 1, child))
        if not children and not element.tail:
            element.tail = '\n' + indent * level

def create_gresource_xml():
    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'])

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

    def add_file_entries(pattern, comment_block=False):
        entries = []
        for basename in base_names:
            file_path = pattern.format(basename=basename)
            entries.append(file_path)

        if comment_block:
            comment_content = '\n'.join(['    <file compressed="true">{}</file>'.format(entry) for entry in entries])
            gresource.append(ET.Comment('\n' + comment_content + '\n'))
        else:
            for entry in entries:
                ET.SubElement(gresource, 'file', compressed="true").text = entry

    add_file_entries("txts/hints/{basename}/hints1_{basename}")
    add_file_entries("txts/hints/{basename}/hints2_{basename}")
    add_file_entries("txts/hints/{basename}/hints2_pre_gtk3_20_{basename}", comment_block=True)
    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(".gresource.xml", "wb") as f:
        tree.write(f, encoding="utf-8", xml_declaration=True)

create_gresource_xml()
