#!/usr/bin/env python

import os
import re
import time

start = time.time()

def find_replace(root_dir, find_text, replace_text, output_file):
    find_words = [word.strip() for word in find_text.split(',')]
    replace_words = [word.strip() for word in replace_text.split(',')]
    if len(find_words)!= len(replace_words):
        print("Error: Number of find words and replace words must be the same. Using only matching pairs.")
        min_len = min(len(find_words), len(replace_words))
        find_words = find_words[:min_len]
        replace_words = replace_words[:min_len]

    html = "<html><body><h1>Files Modified during find-replace operation</h1><ul>"
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.html'):
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r') as f:
                        content = f.read()
                    modified = False
                    modified_words = []
                    for find_word, replace_word in zip(find_words, replace_words):
                        if find_word in content:
                            print(f"Found '{find_word}' in {file_path}")
                            content = content.replace(find_word, replace_word)
                            modified = True
                            modified_words.append(f"{find_word} -> {replace_word}")
                    if modified:
                        with open(file_path, 'w') as f:
                            f.write(content)
                        print(f"Modified {file_path}")
                        html += f"<li><a href='./{file_path}'>{file}</a> - Modified words: {', '.join(modified_words)}</li>"
                except Exception as e:
                    print(f"Error reading {file_path}: {e}")
    html += "</ul></body></html>"
    with open(output_file, 'w') as f:
        f.write(html)
    print("See modified files list in", output_file)



root_dir = './'
find_text = '''वं० माताजी'''
replace_text = '''वन्दनीया माताजी'''


# root_dir = './'
# find_text = 'संवेदना'
# replace_text = 'सम्वेदना'
# find_text = 'old_text'
# replace_text = 'new_text'
output_file ='find-replace-single-word.html'
find_replace(root_dir, find_text, replace_text, output_file)


end = time.time()
print("Elapsed (with compilation) = %s" % (end - start))
