import html
import uuid

import markdown
import streamlit as st

from utils.logger import setup_logger

logger = setup_logger(__name__)

# html_expander remplace st.expander
#
# En effet, st.expander présente un défaut lors de la fermeture
# avec une fois la fermeture terminée, un dernier mouvement
# gênant visuellement.
def html_expander(title, content, open_by_default=False, details_class="", summary_class=""):
    """Creates an HTML details/summary expander with content inside.

    Args:
        title (str): Text to display in the summary/header.
        content (str): Markdown content to display inside the expander.
        open_by_default (bool): Whether the expander is open by default.
        details_class (str): CSS class for the details element.
        summary_class (str): CSS class for the summary element.
    """
    # Generate a unique ID for this expander
    expander_id = f"expander_{uuid.uuid4().hex}"

    # Set attributes
    expanded = "open" if open_by_default else ""
    details_attr = f'class="{details_class}"' if details_class else ""
    summary_attr = f'class="{summary_class}"' if summary_class else ""

    # Convert markdown to HTML (use Python's markdown library)
    try:
        # Try to use markdown package if available
        html_content = markdown.markdown(content)
    except ImportError:
        logger.warning("Module 'markdown' non disponible, utilisation du fallback HTML")
        html_content = html.escape(content).replace('\n', '<br>')
    except Exception as e:
        logger.error(f"Erreur lors de la conversion markdown: {e}", exc_info=True)
        html_content = html.escape(content).replace('\n', '<br>')

    # Build the complete HTML structure
    complete_html = f"""
    <details id="{expander_id}" {expanded} {details_attr}>
        <summary {summary_attr}>{title}</summary>
        <div class="details-content">
            {html_content}
        </div>
    </details>
    """

    # Render the complete HTML in one call
    st.markdown(complete_html, unsafe_allow_html=True)
