import os
import re
import tkinter as tk
from tkinter import filedialog

# Open a file dialog for selecting a folder
root = tk.Tk()
root.withdraw()
folder_selected = filedialog.askdirectory(title="Select Folder")

if folder_selected:
    # Prepare the output file path
    output_file_path = os.path.join(folder_selected, "Extern.txt")
    
    # Open the output file with UTF-8 encoding, overwriting if it exists
    with open(output_file_path, "w", encoding="utf-8") as output_file:
        
        # Iterate over all files in the selected folder
        for file_name in os.listdir(folder_selected):
            # Check if the file is a .txt file and not the output file
            if file_name.endswith(".txt") and file_name != "Extern.txt":
                file_path = os.path.join(folder_selected, file_name)
                
                # Read the content of the file with UTF-8 encoding
                with open(file_path, "r", encoding="utf-8") as input_file:
                    content = input_file.readlines()
                    
                    # Flag to indicate whether any match is found in the file
                    match_found = False
                    
                    # Iterate over each line in the content to find matches
                    for line in content:
                        # Use regex to check if the line matches the specified format
                        if re.match(r"\d{1,2} (Paar|Paare|Mann|Männer|Frau|Frauen) \(Extern\)", line.strip()):
                            # If a match is found for the first time, write the file name
                            if not match_found:
                                output_file.write(file_name.rsplit(".", 1)[0] + "\n")
                                match_found = True
                            
                            # Write the matched line
                            output_file.write(line)
                        
                    # If any match was found, write a newline for separation
                    if match_found:
                        output_file.write("\n")
                        
print("Processing Completed!")

