import streamlit as st
import streamlit.components.v1 as components

# πŸ’‘ If you want to render Mermaid diagrams in pure Streamlit, you can use
#   streamlit-mermaid or other solutions, but here's the direct HTML approach.
# πŸ’Ώ pip install streamlit-mermaid (optional) if you go that route.

# -------------------------------------------
# πŸŽ‰ Default Mermaid code with emojis πŸŽ‰
# -------------------------------------------
DEFAULT_MERMAID = """
flowchart LR
    %% The user is unstoppable
    U((User 😎)) -- "Talk πŸ—£οΈ" --> LLM[LLM Agent πŸ€–\\nExtract Info]
    LLM -- "Query πŸ”" --> HS[Hybrid Search πŸ”Ž\\nVector+NER+Lexical]
    HS -- "Reason πŸ€”" --> RE[Reasoning Engine πŸ› οΈ\\nNeuralNetwork+Medical]
    RE -- "Link πŸ“‘" --> KG((Knowledge Graph πŸ“š\\nOntology+GAR+RAG))
"""

def generate_mermaid_html(mermaid_code: str) -> str:
    """
    🍿 Returns minimal HTML embedding a Mermaid diagram.
    The code is centered using a simple inline style πŸ•Ί
    """
    return f"""
    <html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
        <style>
            /* Quick center alignment: your diagram in spotlight 🀩 */
            .centered-mermaid {{
                display: flex;
                justify-content: center;
                margin: 20px auto;
            }}
        </style>
    </head>
    <body>
        <div class="mermaid centered-mermaid">
            {mermaid_code}
        </div>
        <script>
            mermaid.initialize({{ startOnLoad: true }});
        </script>
    </body>
    </html>
    """

def main():
    st.set_page_config(page_title="Inline Mermaid Demo", layout="wide")
    
    # πŸ”₯ Title for our spiffy app
    st.title("Top-Centered Mermaid Diagram 🏺")

    # πŸ§ͺ Start with default code or user-modified
    if "current_mermaid" not in st.session_state:
        st.session_state["current_mermaid"] = DEFAULT_MERMAID

    # πŸš€ Show the diagram *first*, in the center, via HTML embed
    diagram_html = generate_mermaid_html(st.session_state["current_mermaid"])
    components.html(diagram_html, height=400, scrolling=True)

    # 🌈 Now, place columns for Markdown & Mermaid editing
    left_col, right_col = st.columns(2)

    # --- Left Column: Markdown Editor ---
    with left_col:
        st.subheader("Markdown Side πŸ“")
        markdown_text = st.text_area(
            "Edit Markdown:",
            value="## Hello!\nYou can type *Markdown* here.\n",
            height=400
        )
        
        # πŸ”˜ Button bar: short, sweet, emoji-laden
        colA, colB = st.columns([1,1])
        with colA:
            if st.button("πŸ”„ Refresh Markdown"):
                st.write("**Markdown** content refreshed! 🍿")
        with colB:
            if st.button("❌ Clear Markdown"):
                # 🫧 Bye-bye text
                st.session_state["last_markdown"] = ""
                st.experimental_rerun()

        # Preview the user’s Markdown below
        st.markdown("---")
        st.markdown("**Preview:**")
        st.markdown(markdown_text)

    # --- Right Column: Mermaid Editor ---
    with right_col:
        st.subheader("Mermaid Side πŸ§œβ€β™‚οΈ")
        mermaid_input = st.text_area(
            "Edit Mermaid Code:",
            value=st.session_state["current_mermaid"],
            height=400
        )
        
        # πŸ•ΉοΈ Another lil button bar
        colC, colD = st.columns([1,1])
        with colC:
            if st.button("🎨 Refresh Diagram"):
                st.session_state["current_mermaid"] = mermaid_input
                st.write("**Mermaid** diagram refreshed! 🌈")
                st.experimental_rerun()
        with colD:
            if st.button("❌ Clear Mermaid"):
                st.session_state["current_mermaid"] = ""
                st.experimental_rerun()

        st.markdown("---")
        st.markdown("**Mermaid Source:**")
        st.code(mermaid_input, language="python", line_numbers=True)

    # πŸ¦€ The show is over. Crabs? Possibly. πŸ¦€

if __name__ == "__main__":
    main()