import os
import re

output_filename = "app-design.md"

# Liste aller .js-Dateien im aktuellen Verzeichnis
file_list = [f for f in os.listdir('.') if os.path.isfile(f) and f not in [__file__, output_filename] and f.endswith('.js')]

with open(output_filename, 'w', encoding='utf-8') as outfile:
    for filename in sorted(file_list):
        outfile.write(f"## {filename}\n") # Nur eine neue Zeile

        try:
            with open(filename, 'r', encoding='utf-8', errors='ignore') as infile:
                lines = infile.readlines()
                comment_lines = []
                is_comment_block = False

                for line in lines:
                    stripped_line = line.strip()

                    # Start eines mehrzeiligen Kommentars
                    if stripped_line.startswith('/*') or stripped_line.startswith('/**'):
                        is_comment_block = True
                        comment_lines.append(line)
                        if stripped_line.endswith('*/'):
                            break  # Einzeiliger Block
                        continue

                    # Ende eines mehrzeiligen Kommentars
                    if is_comment_block:
                        comment_lines.append(line)
                        if stripped_line.endswith('*/'):
                            break
                        continue

                    # Einzeilige Kommentare (//)
                    if stripped_line.startswith('//'):
                        comment_lines.append(line)
                        continue

                    # Stoppen, sobald eine nicht-leere, nicht-kommentierte Zeile erreicht wird
                    if stripped_line:
                        break

                if comment_lines:
                    for comment_line in comment_lines:
                        # Bereinigen der Kommentarmarker
                        cleaned_line = re.sub(r'^\s*(?:/\*+|\*+/|//|\*|\s\*|\s?#\s?)', '', comment_line)
                        outfile.write(cleaned_line)

                else:
                    outfile.write("Keine Kommentare am Dateianfang gefunden.\n\n---\n\n")

        except UnicodeDecodeError:
            outfile.write("Datei konnte nicht als Textdatei gelesen werden.\n\n---\n\n")

print(f"Kommentare wurden erfolgreich in '{output_filename}' geschrieben.")