import configparser
import html
import re

def limpiar_texto(texto):
    texto = texto.replace('\\"', '&quot;').replace('"', "").replace('\\n\\n', ' \\n')
    
    texto = re.sub(r'(https?://[^\s<]+)', r'<a href="\1">\1</a>', texto)

    # Separar por líneas para aplicar transformaciones específicas
    lineas = texto.split('\\n')

    lineas_formateadas = []
    for linea in lineas:
        if "PRESENTADO POR" in linea or "PRESENTADA POR" in linea:
            # Envolver en <b> todo hasta el \n
            linea = f"<b>{linea}</b><br>"
        elif linea.startswith("UPDATE") or linea.startswith("ANÁLISIS"):
            # Envolver en <i> todo hasta el \n
            linea = f"<br><br><i>{linea}</i>"

        lineas_formateadas.append(linea)

    # Unir las líneas con <br>
    return '<br>'.join(lineas_formateadas)

def generar_html(ini_file_path):
    config = configparser.ConfigParser(interpolation=None)
    config.optionxform = str  # Mantiene mayúsculas en claves
    config.read(ini_file_path, encoding="utf-8")

    filas = []

    for section in sorted(config.sections(), key=lambda x: int(x)):
        entry = config[section]
        image = entry.get('image', '').strip()
        name = entry.get('name', '').strip()
        description = entry.get('description', '').strip()

        # Limpiar y formatear el texto
        texto_limpio = limpiar_texto(description)

        # Construir HTML para cada fila
        fila_html = f'''
    <tr align="center">
        <td><img src="http://esquizolandia.lyricaltokarev.com/base/evidence/{image.lower()}"></td>
        <td>{html.escape(name)}</td>
        <td>{texto_limpio}</td>
    </tr>'''
        filas.append(fila_html)

    # HTML final
    tabla_html = "<table border='1'>\n" + "\n".join(filas) + "\n</table>"
    return tabla_html


# --- Ejecución principal ---
if __name__ == "__main__":
    ini_path = "entrada.ini"  # Cambiar si el archivo tiene otro nombre
    html_output = generar_html(ini_path)

    with open("salida.html", "w", encoding="utf-8") as f:
        f.write(html_output)

    print("✅ HTML generado como 'salida.html'")
