import os
import nltk
from wordcloud import WordCloud
from nltk.corpus import stopwords
import string
from collections import Counter
import re
from nltk.tokenize import word_tokenize, sent_tokenize
import matplotlib.pyplot as plt

def complete_analyzer(texto_principal, nombre_archivo="resultado_completo.html", language='spanish', mark_text_html="resultado.html", tokenizar=True):
    """
    Generates an HTML with the following sections:
    1) A centered text on the page.
    2) An image generated by the `comun_words` function on the left side.
    3) An image generated by the `comun_words` function on the right side.
    4) Text generated by the `mark_key_terms` function displayed below the images.

    Args:
        texto_principal (str): The text used to generate the images and content.
        nombre_archivo (str): Name of the HTML file to generate.
        language (str): The language for key terms (default is 'spanish').
        mark_text_html (str): The name of the HTML file where the text with highlighted key terms will be generated.
        tokenizar (bool): Whether the text should be tokenized before processing.

    Returns:
        str: Path to the generated HTML file.
    """
    
    try:
        nltk.download('punkt')
        nltk.download('stopwords')
        
        def mark_key_terms(texto, num_palabras=5, language='english', formato="html", nombre_archivo="resultado.html"):
            """
            Detects key terms in the text and highlights them in bold within an HTML file.
            """
            try:
    
                palabras = word_tokenize(texto.lower(), language=language)
                stop_words = stopwords.words(language)
                palabras_filtradas = [palabra for palabra in palabras if palabra.isalpha() and palabra not in stop_words]

               
                palabras_clave = [palabra for palabra, _ in Counter(palabras_filtradas).most_common(num_palabras)]
                # print("Palabras clave detectadas:", palabras_clave) 

               
                if formato == "html":
                    palabras_negrita = {palabra: f"<b>{palabra}</b>" for palabra in palabras_clave}
                else:
                    raise ValueError("Formato no válido. Usa 'html'.")

                
                oraciones = sent_tokenize(texto, language=language)

               
                for i, oracion in enumerate(oraciones):
                    for palabra, palabra_negrita in palabras_negrita.items():
                        oraciones[i] = re.sub(rf'\b{palabra}\b', palabra_negrita, oraciones[i], flags=re.IGNORECASE)

                texto_modificado = ' '.join(oraciones)

               
                carpeta = './html_results'
                if not os.path.exists(carpeta):
                    os.makedirs(carpeta)

             
                file_path = os.path.join(carpeta, nombre_archivo).replace("\\", "/")
                html_resultado = f"""
                    <html>
                    <head>
                        <title>Text</title>
                        <style>
                            body {{
                                font-family: Arial, sans-serif;
                                background-color: #f4f4f4;
                                margin: 0;
                                padding: 0;
                                display: flex;
                                justify-content: center;
                                align-items: center;
                                height: 100vh;
                                text-align: center;
                            }}
                            h1 {{
                                font-size: 2rem;
                                color: #333;
                                margin-bottom: 20px;
                            }}
                            p {{
                                font-size: 1rem;
                                line-height: 1.6;
                                color: #333;
                                max-width: 800px;
                                margin: 0 auto;
                            }}
                        </style>
                    </head>
                    <body>
                        <div>
                            <h1>Text with bolded keywords</h1>
                            <p>{texto_modificado}</p>
                        </div>
                    </body>
                    </html>
                """

               
                with open(file_path, "w", encoding="utf-8") as f:
                    f.write(html_resultado)

                return file_path

            except Exception as e:
                raise Exception(f"Error in mark_key_terms: {e}")
        texto_html = mark_key_terms(texto_principal, num_palabras=5, language=language, formato="html", nombre_archivo=mark_text_html)

        def generate_word_cloud(texto, max_palabras=100):
            """Generates a word cloud from a text"""
            try:
                palabras = word_tokenize(texto.lower()) 

                stop_words = set(stopwords.words(language))
                palabras_filtradas = [palabra for palabra in palabras if palabra not in stop_words and palabra not in string.punctuation]

                palabra_frecuencia = Counter(palabras_filtradas)
                palabras_comunes = dict(palabra_frecuencia.most_common(max_palabras))

                wordcloud = WordCloud(width=800, height=400, background_color='white').generate_from_frequencies(palabras_comunes)

                carpeta = './html_results/images'
                if not os.path.exists(carpeta):
                    os.makedirs(carpeta)

                file_path = os.path.join(carpeta, "wordcloud.png").replace("\\", "/")

                plt.figure(figsize=(10, 5))
                plt.imshow(wordcloud, interpolation='bilinear')
                plt.axis('off')

                plt.savefig(file_path, format='png')
                # plt.show()

                return file_path
            except Exception as e:
                raise Exception(f"Error generating word cloud: {e}")

        img_izquierda = generate_word_cloud(texto_principal, max_palabras=100)

        def comun_words(texto, max_palabras=5, nombre_archivo="grafico_barras.png", tokenizar=True):
            """
            Generates a bar chart with the most frequent words in a text and saves the image in a folder.
            """
            try:
                if tokenizar:
                    palabras = word_tokenize(texto.lower())
                    stop_words = set(stopwords.words(language))
                    palabras_filtradas = [palabra for palabra in palabras if palabra.isalpha() and palabra not in stop_words]
                else:
                    palabras_filtradas = texto.split()

                palabra_frecuencia = Counter(palabras_filtradas)
                palabras_comunes = palabra_frecuencia.most_common(max_palabras)

                palabras, frecuencias = zip(*palabras_comunes)

                plt.figure(figsize=(12, 8))
                barras = plt.bar(palabras, frecuencias, color="#69b3a2", edgecolor="black", linewidth=1.5)

                plt.xlabel('Palabras', fontsize=14, labelpad=15, color="#333")
                plt.ylabel('Frecuencia', fontsize=14, labelpad=15, color="#333")
                plt.title('Most Frequent Words in the Text', fontsize=18, pad=20, color="#444")
                plt.xticks(fontsize=12, rotation=45, ha='right', color="#444")
                plt.yticks(fontsize=12, color="#444")
                plt.grid(axis='y', linestyle='--', linewidth=0.5, alpha=0.7)

                for barra in barras:
                    altura = barra.get_height()
                    plt.text(barra.get_x() + barra.get_width() / 2, altura + 0.5, f'{int(altura)}',
                            ha='center', va='bottom', fontsize=12, color="#444")

                carpeta = './html_results/images'
                if not os.path.exists(carpeta):
                    os.makedirs(carpeta)

                file_path = os.path.join(carpeta, nombre_archivo).replace("\\", "/")

                plt.tight_layout()
                plt.savefig(file_path, format='png', dpi=300)
                # plt.show()

                return file_path
            except Exception as e:
                raise Exception(f"Error generating bar chart: {e}")

        img_derecha = comun_words(texto_principal, max_palabras=5, nombre_archivo="grafico_barras.png", tokenizar=tokenizar)

        html_resultado = f"""
        <html>
        <head>
            <title>Complete result</title>
            <style>
                body {{
                    font-family: Arial, sans-serif;
                    background-color: #f4f4f4;
                    margin: 0;
                    padding: 0;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    flex-direction: column;
                    height: 100vh;
                    color: #333;
                }}
                .container {{
                    background-color: #fff;
                    border-radius: 12px;
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                    padding: 30px;
                    width: 80%;
                    max-width: 1200px;
                    text-align: center;
                    margin-top: 20px;
                    box-sizing: border-box;
                }}
                h1 {{
                    font-size: 2.5rem;
                    color: #444;
                    margin-bottom: 30px;
                    font-weight: 600;
                }}
                iframe {{
                    width: 100%;
                    height: 500px;
                    border: none;
                    margin-top: 20px;
                    border-radius: 8px;
                    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
                }}
                .content {{
                    display: flex;
                    justify-content: space-between;
                    margin-top: 40px;
                    gap: 20px;
                }}
                .left, .right {{
                    width: 48%;
                    height: auto;
                    text-align: center;
                    box-sizing: border-box;
                }}
                h2 {{
                    font-size: 1.5rem;
                    color: #555;
                    margin-bottom: 10px;
                }}
                img {{
                    width: 100%;
                    height: auto;
                    max-height: 400px;
                    border-radius: 10px;
                    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
                }}
                p {{
                    font-size: 1rem;
                    line-height: 1.6;
                    color: #333;
                    max-width: 800px;
                    margin: 20px auto;
                    font-weight: 400;
                }}
                @media (max-width: 768px) {{
                    .content {{
                        flex-direction: column;
                        align-items: center;
                    }}
                    .left, .right {{
                        width: 90%;
                        margin-bottom: 20px;
                    }}
                    iframe {{
                        height: 400px;
                    }}
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1>Main Text</h1>
                <iframe src="{'.'+texto_html}"></iframe>
                <div class="content">
                    <div class="left">
                        <h2>Wordcloud Graph</h2>
                        <img src="{'.'+img_izquierda}" alt="Left graph">
                    </div>
                    <div class="right">
                        <h2>Word count</h2>
                        <img src="{'.'+img_derecha}" alt="Right graph">
                    </div>
                </div>
            </div>
        </body>
        </html>
        """

        carpeta = './html_results'
        if not os.path.exists(carpeta):
            os.makedirs(carpeta)

        file_path = os.path.join(carpeta, nombre_archivo).replace("\\", "/")
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(html_resultado)

        return f"Archivo HTML guardado como {file_path}"

    except Exception as e:
        return f"Error en el análisis: {str(e)}"

# texto2 = 'Happiness often hides in the simple things: the sound of leaves rustling in the wind, the warm embrace of someone you love, or that song that makes you dance without realizing it. It’s a state we create with the little details, a spark that lights up our hearts when we allow ourselves to savor the present moment. '
# print(complete_analyzer(texto2))