import os
import unicodedata

def remove_accents(text):
    text = unicodedata.normalize('NFD', text)
    text = text.encode('ascii', 'ignore')
    text = text.decode("utf-8")
    return str(text)

def remove_accents2(input_str):
    nfkd_form = unicodedata.normalize('NFKD', input_str)
    return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])

folder = input("Ce folder analizati : ")
files = os.listdir(folder)
lst = []

n = int(input("Introduceti cate cuvinte cheie doriti sa cautati : "))
keys = []

for i in range(0, n):
    koi = str(input())
    keys.append(remove_accents(koi))

# Create result.txt in the input folder
result_path = os.path.join(folder, 'result.txt')
if os.path.exists(result_path):
    os.remove(result_path)  # Remove existing result.txt if it exists

for file in files:
    if '.txt' in file:
        f = open(os.path.join(folder, file), encoding='utf-8')
        data = f.read()
        data = remove_accents(data)
        f.close()
        
        visited = []
        for key in keys:
            if key in str(data) and key not in visited:
                visited += [key]
                
        if len(visited) == len(keys):
            with open(result_path, 'a', encoding='ISO-8859-2') as f2:
                f2.write(data)
                f2.write('\r')

# Open the result file automatically
if os.path.exists(result_path):
    os.startfile(result_path)  # Windows
    # Pentru Linux: os.system(f'xdg-open "{result_path}"')
    # Pentru MacOS: os.system(f'open "{result_path}"')