#!/usr/bin/env python

import os
import re

def search_sentences(root_dir, output_file, output_file_total):
    html_template = """
    <html>
    <head>
    <meta http-equiv='content-type' content='text/html; charset=UTF-8'>
    <meta charset='utf-8'>
    </head>
    <body>
    <h1>Search Results</h1>
    <div id="search-container">
    <input type="search" id="search-input" placeholder="Search questions...">
    <button id="search-button">Enter your question</button> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="../search/search.html" target='_blank' > आपकी महत्त्वपूर्ण जिज्ञासाएँ - पूज्य गुरुसत्ता के समाधान</a>
    </div>

    <script>
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        let currentIndex = 0;

        searchButton.addEventListener('click', () => {
            // Get the search term from the input field
            const searchTerms = searchInput.value.trim().split(' ');

            // Iterate through the list of links and check if the search term is present in the linked text
            const links = document.querySelectorAll('a');
            const highlightedLinks = Array.from(links).filter((link) => {
                const linkText = link.textContent.toLowerCase();
                return searchTerms.every((term) => linkText.includes(term.toLowerCase()));
            });

            // Remove existing highlights
            links.forEach((link) => {
                link.innerHTML = link.textContent;
            });

            // Highlight the matched words in the linked text
            highlightedLinks.forEach((link, index) => {
                const highlightedText = searchTerms.reduce((text, term) => text.replace(new RegExp(term, 'gi'), (match) => `<mark>${match}</mark>`), link.textContent);
                link.innerHTML = highlightedText;
            });

            // Jump to the highlighted link
            if (currentIndex < highlightedLinks.length) {
                highlightedLinks[currentIndex].style.fontWeight = 'bold';
                highlightedLinks[currentIndex].scrollIntoView({ behavior:'smooth' });
                currentIndex++;
                if (currentIndex >= highlightedLinks.length) {
                    currentIndex = 0;
                }
            }
        });
    </script>

    <script>function copySentence(event) {navigator.clipboard.writeText(event.target.textContent);}</script>
    <div id='google_translate_element'></div>
    <script type='text/javascript'>function googleTranslateElementInit() {new google.translate.TranslateElement({pageLanguage: 'hi', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');}</script>
    <script type='text/javascript' src='//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'></script>
    <ul>
    """

    html_total_template = """
    <html>
    <head>
    <meta http-equiv='content-type' content='text/html; charset=UTF-8'>
    <meta charset='utf-8'>
    </head>
    <body>
    <h1>Total Search Results</h1>
    <div id="search-container">
    <input type="search" id="search-input" placeholder="Search questions...">
    <button id="search-button">Enter your question</button> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="../search/search.html" target='_blank' > आपकी महत्त्वपूर्ण जिज्ञासाएँ - पूज्य गुरुसत्ता के समाधान</a>
    </div>

    <script>
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        let currentIndex = 0;

        searchButton.addEventListener('click', () => {
            // Get the search term from the input field
            const searchTerms = searchInput.value.trim().split(' ');

            // Iterate through the list of links and check if the search term is present in the linked text
            const links = document.querySelectorAll('a');
            const highlightedLinks = Array.from(links).filter((link) => {
                const linkText = link.textContent.toLowerCase();
                return searchTerms.every((term) => linkText.includes(term.toLowerCase()));
            });

            // Remove existing highlights
            links.forEach((link) => {
                link.innerHTML = link.textContent;
            });

            // Highlight the matched words in the linked text
            highlightedLinks.forEach((link, index) => {
                const highlightedText = searchTerms.reduce((text, term) => text.replace(new RegExp(term, 'gi'), (match) => `<mark>${match}</mark>`), link.textContent);
                link.innerHTML = highlightedText;
            });

            // Jump to the highlighted link
            if (currentIndex < highlightedLinks.length) {
                highlightedLinks[currentIndex].style.fontWeight = 'bold';
                highlightedLinks[currentIndex].scrollIntoView({ behavior:'smooth' });
                currentIndex++;
                if (currentIndex >= highlightedLinks.length) {
                    currentIndex = 0;
                }
            }
        });
    </script>
    <script>function copySentence(event) {navigator.clipboard.writeText(event.target.textContent);}</script>
    <div id='google_translate_element'></div>
    <script type='text/javascript'>function googleTranslateElementInit() {new google.translate.TranslateElement({pageLanguage: 'hi', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');}</script>
    <script type='text/javascript' src='//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'></script>
    <ul>
    """

    all_sentences = []
    sentences = []
    titles = set()
    for root, dirs, files in os.walk(root_dir):
        html = html_template
        html_total = html_total_template
        dirs.sort()
        files.sort()
        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()
                        p_elements = re.findall(r'<p>(.*?)</p>', content, re.DOTALL)
                        p_elements = [p_element for p_element in p_elements if p_element.strip()]
                        full_text =''.join(p_elements)
                        for i, p_element in enumerate(p_elements):
                            found_sentences = re.findall(r"[^.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>{}।!?]*\?", p_element)
                            for sentence in found_sentences:
                                words = sentence.split()
                                if len(words) >= 3:
                                    title = sentence +' '+ full_text[full_text.find(sentence) + len(sentence):].strip()
                                    title = re.sub('<.*?>', '', title)
                                    stop_chars = ['।','?','॥','.']
                                    title_end_index = len(sentence) + 315
                                    for char in stop_chars:
                                        index = title[:title_end_index].rfind(char)
                                        if index!= -1:
                                            title_end_index = index + 1
                                            break
                                    title = title[:title_end_index].strip()
                                    if title not in titles:
                                        titles.add(title)
                                        sentences.append((sentence, file_path, title))
                                        all_sentences.append((sentence, file_path, title))
                except Exception as e:
                    print(f"Error reading {file_path}: {e}")
        if sentences:
            sentences.sort(key=lambda x: x[0].lower())
            for sentence, file_path, title in sentences:
                html += f"<li><a href='{os.path.relpath(file_path, root)}' target='_blank' title='{title}' onclick='copySentence(event)'>{sentence}</a>...{title[len(sentence)-1:len(sentence)+100] if title.startswith(sentence) else title[len(sentence)-1:len(sentence)+100]}...</li>\n"
            html += "</ul></body></html>"
            output_path = os.path.join(root, output_file)
            with open(output_path, 'w') as f:
                f.write(html)
            print(f"Output file created: {output_path}")
            html = html_template
            sentences = []
    all_sentences.sort(key=lambda x: x[0].lower())
    for sentence, file_path, title in all_sentences:
        sentence = re.sub('<.*?>', '', sentence)
        html_total += f"<li><a href='{os.path.relpath(file_path, root)}' target='_blank' title='{title}' onclick='copySentence(event)'>{sentence}</a>...{title[len(sentence)-1:len(sentence)+100] if title.startswith(sentence) else title[len(sentence)-2:len(sentence)+100]}...</li>\n"
    html_total += "</ul></body></html>"
    output_path_total = os.path.join(root, output_file_total)
    with open(output_path_total, 'w') as f:
        f.write(html_total)
    print(f"Total output file created: {output_path_total}")

print("Starting search...")
root_dir = './'
output_file ='search_sentences_title.html'
output_file_total ='search_sentences_total.html'
search_sentences(root_dir, output_file, output_file_total)
print("Search completed.")
