import streamlit as st
import logging
import io
import sys

# Configure logging
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')

def app(environ, start_response):
    status = '200 OK'
    output_buffer = io.StringIO()
    
    # Set Streamlit configuration options
    st._config.set_option('server.headless', True)
    st._config.set_option('browser.serverPort', 0)
    
    # Redirect Streamlit's stdout to our buffer
    old_stdout = sys.stdout
    sys.stdout = output_buffer
    
    try:
        # Your Streamlit app logic here
        st.title("AI Web Miner")
        url = st.text_input("Entre l url du site web")

        if st.button("Scrape le site"):
            st.write("scraping le site web")
            logging.info("Button clicked: Scraping website")

    finally:
        # Reset stdout back to its original value
        sys.stdout = old_stdout

    # Capture the Streamlit app's output
    output = output_buffer.getvalue()
    
    # Log the output to see what's being generated
    logging.info(f"Generated HTML: {output}")

    response_headers = [('Content-type', 'text/html'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    
    return [output.encode('utf-8')]

# Assign the function directly
streamlit_app = app