import streamlit as st
import os
import json
from PIL import Image

st.set_page_config(page_title="๐Ÿง ๐Ÿ“–โœ๏ธRemixable AI๐ŸŽจ๐Ÿ““๐Ÿ‘จโ€๐Ÿซ", page_icon="๐Ÿ‰", layout="wide")

glossary = {
    "๐Ÿ’‰ Vaccinate": ["mRNA vaccines", "Nanoparticle delivery systems", "Universal flu vaccine"],
    "๐Ÿฉบ Diagnose": ["AI-driven diagnostic tools", "Wearable health monitors", "Liquid biopsies"],
    "๐Ÿฅ Hospital": ["Telemedicine", "Robot-assisted surgery", "Smart hospitals"],
    "๐Ÿš‘ Emergency": ["Point-of-care testing", "Drone delivery for medical supplies", "Mobile stroke units"],
    "๐Ÿ’Š Meds": ["Precision medicine", "Biologics for chronic diseases", "Pharmacogenomics"],
    "๐Ÿฉน Bandage": ["Smart bandages", "Biodegradable bandages", "Hydrogel bandages"],
    "๐Ÿงฌ DNA": ["Gene editing (CRISPR-Cas9)", "Gene therapy for inherited diseases", "Synthetic biology"],
    "๐Ÿ”ฌ Research": ["Big Data in healthcare", "3D bioprinting of tissues", "Nanotechnology in medicine"],
    "๐ŸŒก๏ธ Temperature": ["Wearable temperature monitors", "Infrared thermography", "Microfluidic devices"],
    "๐Ÿ Nutrition": ["Personalized nutrition", "Nutrigenomics", "Functional foods"],
}

# Directory to store scores
score_dir = "scores"
os.makedirs(score_dir, exist_ok=True)

# Function to generate a unique key for each button
def generate_key(label, header, idx):
    return f"{header}_{label}_{idx}"

# Function to increment score and save it
def update_score(key, increment=1):
    score_file = os.path.join(score_dir, f"{key}.json")
    if os.path.exists(score_file):
        with open(score_file, "r") as file:
            score_data = json.load(file)
    else:
        score_data = {"clicks": 0, "score": 0}
    
    score_data["clicks"] += 1
    score_data["score"] += increment
    
    with open(score_file, "w") as file:
        json.dump(score_data, file)
    
    return score_data["score"]

# Function to load score
def load_score(key):
    score_file = os.path.join(score_dir, f"{key}.json")
    if os.path.exists(score_file):
        with open(score_file, "r") as file:
            score_data = json.load(file)
        return score_data["score"]
    return 0

# Function to display the glossary for a selected area
def display_glossary(area):
    st.subheader(f"Glossary for {area}")
    terms = glossary[area]
    for term in terms:
        st.write(f"- {term}")

# Display headers and buttons with scores
def display_buttons_with_scores():
    headers = ["Inputs", "Outputs", "Health", "Learning", "AI", "Writing"]
    buttons = [
        ["๐Ÿ“ Text", "๐Ÿ“– Read", "๐Ÿ“ท Photo", "๐Ÿ–ผ๏ธ View", "๐ŸŽ™๏ธ Record", "๐ŸŽง Listen", "๐ŸŽฅ Video", "๐Ÿ“น Capture"],
        ["๐Ÿ’ฌ Chat", "โœ๏ธ Write", "๐ŸŽจ Art", "๐ŸŒ„ Create", "๐ŸŽต Music", "๐ŸŽถ Compose", "๐Ÿ“ผ Watch", "๐Ÿฟ Movies"],
        ["๐Ÿ’‰ Vaccinate", "๐Ÿฉบ Diagnose", "๐Ÿฅ Hospital", "๐Ÿš‘ Emergency", "๐Ÿ’Š Meds", "๐Ÿฉน Bandage", "๐Ÿงฌ DNA", "๐Ÿ”ฌ Research", "๐ŸŒก๏ธ Temperature", "๐Ÿ Nutrition"],
        ["๐Ÿ“š Study", "๐Ÿง  Brain", "๐Ÿ‘ฉโ€๐ŸŽ“ Graduate", "๐Ÿ“ Measure", "๐Ÿ” Search", "๐Ÿ“Š Analyze", "๐Ÿ“‹ Plan", "๐Ÿ–‹๏ธ Write", "๐Ÿ‘จโ€๐Ÿซ Teach", "๐Ÿงฉ Puzzle"],
        ["๐Ÿค– Robot", "๐Ÿ‘พ Game", "๐Ÿ’ป Code", "๐Ÿงฎ Calculate", "๐Ÿ“ก Connect", "๐Ÿ”‹ Power", "๐Ÿ•น๏ธ Play", "๐Ÿ–ฅ๏ธ Display", "๐Ÿง‘โ€๐Ÿ’ป Develop", "๐Ÿ‘จโ€๐Ÿ”ฌ Experiment"],
        ["โœ๏ธ Author", "๐Ÿ“ Note", "๐Ÿ–Š๏ธ Pen", "๐Ÿ–‹๏ธ Sign", "๐Ÿ“š Library", "๐Ÿ”– Bookmark", "๐Ÿ““ Journal", "โœ’๏ธ Ink", "๐Ÿ“œ Scroll"]
    ]

    cols = st.columns(len(headers))
    for idx, (col, header, buttons_list) in enumerate(zip(cols, headers, buttons)):
        with col:
            st.markdown(f"### {header}")
            for button_idx, button_label in enumerate(buttons_list, start=1):
                key = generate_key(button_label, header, button_idx)
                score = load_score(key)
                if st.button(f"{button_label} {score}", key=key):
                    new_score = update_score(key)
                    # Reload the page to reflect the updated score
                    st.experimental_rerun()

    # Display buttons for each area
    cols = st.columns(5)
    for i, (area, terms) in enumerate(glossary.items()):
        if cols[i % 5].button(area):
            display_glossary(area)
 
# Main application logic
if __name__ == "__main__":
    st.markdown('# Remixable!')
    display_buttons_with_scores()

def fetch_wikipedia_summary(keyword):
    # Placeholder function for fetching Wikipedia summaries
    # In a real app, you might use requests to fetch from the Wikipedia API
    return f"Summary for {keyword}. For more information, visit Wikipedia."

def create_search_url_youtube(keyword):
    base_url = "https://www.youtube.com/results?search_query="
    return base_url + keyword.replace(' ', '+')

def create_search_url_bing(keyword):
    base_url = "https://www.bing.com/search?q="
    return base_url + keyword.replace(' ', '+')

def create_search_url_wikipedia(keyword):
    base_url = "https://www.wikipedia.org/search-redirect.php?family=wikipedia&language=en&search="
    return base_url + keyword.replace(' ', '+')

def create_search_url_google(keyword):
    base_url = "https://www.google.com/search?q="
    return base_url + keyword.replace(' ', '+')

def display_images_and_wikipedia_summaries():
    st.title('Gallery with Related Stories')
    image_files = [f for f in os.listdir('.') if f.endswith('.png')]
    if not image_files:
        st.write("No PNG images found in the current directory.")
        return
    
    for image_file in image_files:
        image = Image.open(image_file)
        st.image(image, caption=image_file, use_column_width=True)
        
        keyword = image_file.split('.')[0]  # Assumes keyword is the file name without extension
        
        # Display Wikipedia and Google search links
        wikipedia_url = create_search_url_wikipedia(keyword)
        google_url = create_search_url_google(keyword)
        youtube_url = create_search_url_youtube(keyword)
        bing_url = create_search_url_bing(keyword)
        
        links_md = f"""
        [Wikipedia]({wikipedia_url}) | 
        [Google]({google_url}) | 
        [YouTube]({youtube_url}) | 
        [Bing]({bing_url})
        """
        st.markdown(links_md)

display_images_and_wikipedia_summaries()

st.markdown('# ๐Ÿฉบ Remixable AI/UI/UX for Healers by Aaron Wacker')

def get_all_query_params(key):
    return st.query_params().get(key, [])

def clear_query_params():
    st.query_params()  

st.markdown("### Query Parameters - These Deep Link Map to Remixable Methods")
st.write("Current Query Parameters:", st.query_params)

# Example: Using query parameters to navigate or trigger functionalities
if 'action' in st.query_params:
    action = st.query_params()['action'][0]  # Get the first (or only) 'action' parameter
    if action == 'show_message':
        st.success("Showing a message because 'action=show_message' was found in the URL.")
    elif action == 'clear':
        clear_query_params()
        st.experimental_rerun()

# Handling repeated keys
if 'multi' in st.query_params:
    multi_values = get_all_query_params('multi')
    st.write("Values for 'multi':", multi_values)

# Manual entry for demonstration
st.write("Enter query parameters in the URL like this: ?action=show_message&multi=1&multi=2")

# Clear query parameters button
if st.button("Clear Query Parameters"):
    clear_query_params()
    st.experimental_rerun()