import os
import openai
import streamlit as st
from langchain.agents import load_tools, initialize_agent
from langchain.llms import OpenAI
import time
from streamlit_option_menu import option_menu
def initialize_tools_and_agent(openai_api_key):
    llm = OpenAI(temperature=0,openai_api_key=openai_api_key)
    tools = load_tools(["llm-math"], llm=llm)
    agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
    return agent
# Set Streamlit page configuration
st.set_page_config(page_title='Math ChatGPT4', 
                   page_icon=":memo:", 
                    layout='wide', 
                   initial_sidebar_state='collapsed')
st.title('Mathematical Puzzles Solving Tool')
#st.header('Language Model App. for Mathematical Puzzle Solver')
# Set CSS properties for HTML components
st.markdown("""
    """, unsafe_allow_html=True)
hide_style='''
    
'''
with st.sidebar:
    selected = option_menu("Main Menu", ["Home", 'Help'], 
        icons=['house', 'gear'], menu_icon="cast", default_index=0)
    selected
    hide_style='''
    
'''
hide_streamlit_style = """
                
                """
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
st.markdown("""
""", unsafe_allow_html=True)
if selected=="Help":
    st.markdown(hide_style,unsafe_allow_html=True)
   # st.title("Help")
    # Import required libraries
    import streamlit as st
    # Set Streamlit page configuration
    #st.set_page_config(page_title='Help - XLS Office Documents Analysis with ChatGPT4 NLP Model', 
                      # page_icon=":memo:", 
                      # layout='wide', 
                      # initial_sidebar_state='collapsed')
    import streamlit as st
    # Set CSS properties for HTML components
    st.markdown("""
    
    """, unsafe_allow_html=True)
    # Display application title
  #  st.markdown("""
   # ChatGPT-4 Bot: Puzzle Solving and Imagination Companion
   # Your Partner for Puzzles and Creative Adventures
   # """, unsafe_allow_html=True)
    ## Display authorship details
   # st.markdown("""
    ## Developed by [Your Name]
   # * AI Enthusiast
   # * Expert in AI-driven Conversations
   # """, unsafe_allow_html=True)
    # Display application introduction
    st.markdown("""
    ### Welcome to ChatGPT-4 Bot!
    Introducing your versatile AI companion, ChatGPT-4 Bot. This interactive tool is designed to be your guide for solving mathematical puzzles . Whether you're a curious kid, a young learner, or simply looking to exercise your mind, ChatGPT-4 Bot is here to assist.
    ### Dive into Puzzle Challenges
    Are math puzzles your thing? ChatGPT-4 Bot is equipped to help you tackle a variety of mathematical challenges. From solving equations to deciphering number patterns, this AI-powered tool is your partner in puzzle-solving.
    ### How to Interact
    Puzzles Mode: Input math-related questions or challenges and receive step-by-step solutions.
     ### Who Can Benefit
    - Students seeking assistance with math problems
   
    - Curious minds interested in AI-driven conversations
    ### Get in Touch
    If you have any inquiries or suggestions, don't hesitate to get in touch. Let's embark on a journey of exploration and learning together!
    """, unsafe_allow_html=True)
    #-----------------
hide_style='''
    
'''
st.markdown(hide_style,unsafe_allow_html=True)
if selected=="Home":
    openai_api_key = st.sidebar.text_input('OpenAI API Key', type="password")
    question_examples = [
        "A store sells oranges in packs of 5 and apples in packs of 8. If John bought 7 packs of oranges and 4 packs of apples, how many fruits did he buy in total?",
        "A box contains 24 red balls and 36 blue balls. If 30% of the red balls and 40% of the blue balls are removed, how many balls are left in the box?",
        "A company has 800 employees. If 25% of the employees are managers and the rest are regular employees, how many regular employees are there in the company?",
        "A classroom has a total of 35 students. If 40% of the students are boys, how many girls are there in the classroom?",
        # Add more examples as needed
    ]
    # Dropdown select box for question examples
    selected_example = st.selectbox('Choose a question example:', question_examples)
    # Pre-populate the question field with the selected example
   # question = st.text_input('Enter your question:', value=selected_example)
    math_question = st.text_area("selected example or write any puzzle and press enter:", value=selected_example)
    if not openai_api_key or not openai_api_key.startswith('sk-'):
        st.warning('Please enter your OpenAI API key!', icon='⚠️')
    else:
        if st.button('Solve'):
            try:
                    agent = initialize_tools_and_agent(openai_api_key)
                    response = agent.run(math_question)
                    with st.spinner('Solving...'):
                        time.sleep(2)  # Simulate processing time
                    st.success('Solved!')
                    st.markdown(f"**The Solution Is:**\n\n{response}")
                    if(response=="Agent stopped due to iteration limit or time limit."):
                        st.warning('Please enter your Puzzle!mathmatical tool', icon='⚠️')
            except openai.error.OpenAIError as e:
                    #st.error(f"An error occurred: {e}")
                    st.warning('Please enter your puzzle! mathmatical tool', icon='⚠️')
            except Exception as e:
                    #st.error(f"An unexpected error occurred: {e}")
                    st.warning('Please enter your puzzle!mathmatical tool', icon='⚠️')