#!/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]

    script_dir = os.path.dirname(os.path.abspath(__file__))
    html = "<html><body><h1>Files Modified during find-replace operation</h1><ul>"

    for root, dirs, files in os.walk(root_dir):
        # Skip the root directory where the script is placed
        if root == script_dir:
            continue

        for file in files:
            if file.endswith('.html'):
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r', encoding='utf-8') 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', encoding='utf-8') 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', encoding='utf-8') as f:
        f.write(html)
    print("See modified files list in", output_file)

root_dir = './'
find_text = '''पूज्य गुरुदेव'''
replace_text = '''गुरुदेव'''

# find_text = '''पूज्य गुरुदेव'''
# replace_text = '''<a href="../folders-special/hamari-vasiyat-aur-virasat.html" target="blank">पूज्य गुरुदेव</a>'''

output_file = 'find-replace-single-word-with-root-files.html'
find_replace(root_dir, find_text, replace_text, output_file)

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