import os
import json
from bs4 import BeautifulSoup

EXEL_EXPORT_PATH = 'C:/Users/Usuario/Desktop/Webcretaria'

# Rutas para tu script de búsqueda (relativa a la raíz de la exportación)
SEARCH_JS_PATH = 'js/search.js'
SEARCH_INDEX_JSON_PATH = 'search_index.json' # El JSON se generará en la raíz de la exportación

# URL de la CDN de Lunr.js (¡esta no requiere descarga manual!)
LUNR_CDN_URL = 'https://unpkg.com/lunr/lunr.min.js'

# HTML del buscador que se inyectará en cada página
SEARCH_HTML_BLOCK = """
<div id="buscador-wrapper" style="padding: 10px; background-color: #f0f0f0; border-bottom: 1px solid #ddd; margin-bottom: 15px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
    <input type="text" id="search-input" placeholder="Buscar en la Webcretaría..." style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 1em;">
    <ul id="search-results" style="list-style: none; padding: 0; margin-top: 10px; max-height: 250px; overflow-y: auto; border-top: 1px solid #eee;"></ul>
</div>
<style>
    #search-results li {
        margin-bottom: 5px;
        padding-bottom: 3px;
        border-bottom: 1px dotted #eee;
    }
    #search-results li:last-child {
        border-bottom: none;
    }
    #search-results li a {
        color: #007bff;
        text-decoration: none;
        display: block;
        padding: 2px 0;
    }
    #search-results li a:hover {
        text-decoration: underline;
    }
    #search-results li strong {
        background-color: #ffe0b2;
        padding: 1px 3px;
        border-radius: 2px;
    }
</style>
"""

# --- FIN CONFIGURACIÓN ---

def generate_search_index_and_inject_code(export_path):
    documents = []
    doc_id = 0

    print(f"Iniciando procesamiento de archivos HTML en: {export_path}")

    # Paso 1: Generar el índice de búsqueda (search_index.json)
    for root, _, files in os.walk(export_path):
        for file in files:
            if file.endswith('.html'):
                file_path = os.path.join(root, file)
                # La URL debe ser relativa a la raíz del sitio para Lunr.js
                relative_url = os.path.relpath(file_path, export_path).replace(os.sep, '/')

                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        html_content = f.read()

                    soup = BeautifulSoup(html_content, 'html.parser')

                    # Extraer título
                    title_tag = soup.find('title')
                    title = title_tag.get_text(strip=True) if title_tag else os.path.splitext(file)[0].replace('_', ' ').title()

                    # Extraer contenido principal
                    content_div = soup.find('div', class_='content-container')
                    if not content_div:
                        content_div = soup.find('div', id='main')
                    if not content_div:
                        content_div = soup.find('article', class_='content-article')
                    if not content_div:
                        content_div = soup.find('body') # Fallback

                    content = ""
                    if content_div:
                        for s in content_div(["script", "style"]):
                            s.extract()
                        for tag in content_div.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'li', 'span', 'div']):
                            content += tag.get_text(separator=' ', strip=True) + " "
                        content = ' '.join(content.split())

                    documents.append({
                        'id': doc_id,
                        'title': title,
                        'url': relative_url,
                        'content': content
                    })
                    doc_id += 1

                except Exception as e:
                    print(f"Error procesando {file_path}: {e}")

    # Guardar el índice JSON
    json_output_path = os.path.join(export_path, SEARCH_INDEX_JSON_PATH)
    try:
        with open(json_output_path, 'w', encoding='utf-8') as f:
            json.dump(documents, f, ensure_ascii=False, indent=2)
        print(f"\nÍndice de búsqueda generado en: {json_output_path} con {len(documents)} documentos.")
    except Exception as e:
        print(f"Error al guardar el índice JSON: {e}")
        return

    # Paso 2: Inyectar el código del buscador en todas las páginas HTML
    print("\nInyectando el buscador en las páginas HTML...")
    for root, _, files in os.walk(export_path):
        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:
                        html_content = f.read()

                    soup = BeautifulSoup(html_content, 'html.parser')

                    # 1. Inyectar el bloque HTML del buscador
                    target_div = soup.find('div', class_='nav-wrapper')
                    if not target_div:
                        target_div = soup.find('div', class_='content-wrapper')

                    if target_div:
                        new_search_div = BeautifulSoup(SEARCH_HTML_BLOCK, 'html.parser')
                        target_div.insert(0, new_search_div)
                        print(f"  Inyectado buscador en {file} (dentro de {target_div.name} class/id)")
                    else:
                        body_tag = soup.find('body')
                        if body_tag:
                            new_search_div = BeautifulSoup(SEARCH_HTML_BLOCK, 'html.parser')
                            body_tag.insert(1, new_search_div)
                            print(f"  Inyectado buscador al principio del body de {file}")
                        else:
                            print(f"  No se pudo encontrar un lugar de inyección adecuado en {file}")

                    # 2. Inyectar las etiquetas <script>
                    # Para tu search.js, la ruta debe ser relativa al archivo HTML actual
                    current_dir = os.path.dirname(file_path)
                    relative_search_path = os.path.relpath(os.path.join(export_path, SEARCH_JS_PATH), current_dir).replace(os.sep, '/')

                    # Script de Lunr.js desde la CDN (¡no requiere descarga!)
                    script_tag_lunr_cdn = soup.new_tag("script", src=LUNR_CDN_URL)
                    # Tu script de búsqueda local
                    script_tag_search_local = soup.new_tag("script", src=relative_search_path)

                    body_tag = soup.find('body')
                    if body_tag:
                        body_tag.append(script_tag_lunr_cdn)
                        body_tag.append(script_tag_search_local)
                    else:
                        print(f"Advertencia: No se encontró la etiqueta <body> en {file}. No se pudieron inyectar los scripts.")

                    # Guardar el HTML modificado
                    with open(file_path, 'w', encoding='utf-8') as f:
                        f.write(str(soup))

                except Exception as e:
                    print(f"Error al procesar/inyectar en {file_path}: {e}")
    print("\n¡Proceso de inyección completado!")

if __name__ == "__main__":
    if not os.path.exists(EXEL_EXPORT_PATH):
        print(f"ERROR: La ruta de exportación '{EXEL_EXPORT_PATH}' no existe.")
        print("Por favor, asegúrate de que eXeLearning haya exportado el contenido y ajusta la variable EXEL_EXPORT_PATH en el script.")
    else:
        generate_search_index_and_inject_code(EXEL_EXPORT_PATH)