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

# Set page configuration with a title and favicon
st.set_page_config(page_title="🌌🚀 Transhuman Space Encyclopedia", page_icon="🌠", layout="wide")

# Ensure the directory for storing scores exists
score_dir = "scores"
os.makedirs(score_dir, exist_ok=True)

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

# Function to increment and save score
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

# Transhuman Space glossary with full content
transhuman_glossary = {
    "🚀 Core Technologies": ["Nanotechnology🔬", "Artificial Intelligence🤖", "Quantum Computing💻", "Spacecraft Engineering🛸", "Biotechnology🧬", "Cybernetics🦾", "Virtual Reality🕶️", "Energy Systems⚡", "Material Science🧪", "Communication Technologies📡"],
    "🌐 Nations": ["Terran Federation🌍", "Martian Syndicate🔴", "Jovian Republics🪐", "Asteroid Belt Communities🌌", "Venusian Colonies🌋", "Lunar States🌖", "Outer System Alliances✨", "Digital Consciousness Collectives🧠", "Transhumanist Enclaves🦿", "Non-Human Intelligence Tribes👽"],
    "💡 Memes": ["Post-Humanism🚶‍♂️➡️🚀", "Neo-Evolutionism🧬📈", "Digital Ascendancy💾👑", "Solar System Nationalism🌞🏛", "Space Explorationism🚀🛰", "Cyber Democracy🖥️🗳️", "Interstellar Environmentalism🌍💚", "Quantum Mysticism🔮💫", "Techno-Anarchism🔌🏴", "Cosmic Preservationism🌌🛡️"],
    "🏛 Institutions": ["Interstellar Council🪖", "Transhuman Ethical Standards Organization📜", "Galactic Trade Union🤝", "Space Habitat Authority🏠", "Artificial Intelligence Safety Commission🤖🔒", "Extraterrestrial Relations Board👽🤝", "Quantum Research Institute🔬", "Biogenetics Oversight Committee🧫", "Cyberspace Regulatory Agency💻", "Planetary Defense Coalition🌍🛡"],
    "🔗 Organizations": ["Neural Network Pioneers🧠🌐", "Spacecraft Innovators Guild🚀🛠", "Quantum Computing Consortium💻🔗", "Interplanetary Miners Union⛏️🪐", "Cybernetic Augmentation Advocates🦾❤️", "Biotechnological Harmony Group🧬🕊", "Stellar Navigation Circle🧭✨", "Virtual Reality Creators Syndicate🕶️🎨", "Renewable Energy Pioneers⚡🌱", "Transhuman Rights Activists🦿📢"],
    "⚔️ War": ["Space Warfare Tactics🚀⚔️", "Cyber Warfare🖥️🔒", "Biological Warfare🧬💣", "Nanotech Warfare🔬⚔️", "Psychological Operations🧠🗣️", "Quantum Encryption & Decryption🔐💻", "Kinetic Bombardment🚀💥", "Energy Shield Defense🛡️⚡", "Stealth Spacecraft🚀🔇", "Artificial Intelligence Combat🤖⚔️"],
    "🎖 Military": ["Interstellar Navy🚀🎖", "Planetary Guard🌍🛡", "Cybernetic Marines🦾🔫", "Nanotech Soldiers🔬💂", "Space Drone Fleet🛸🤖", "Quantum Signal Corps💻📡", "Special Operations Forces👥⚔️", "Artificial Intelligence Strategists🤖🗺️", "Orbital Defense Systems🌌🛡️", "Exoskeleton Brigades🦾🚶‍♂️"],
    "🦹 Outlaws": ["Pirate Fleets🏴‍☠️🚀", "Hacktivist Collectives💻🚫", "Smuggler Caravans🛸💼", "Rebel AI Entities🤖🚩", "Black Market Biotech Dealers🧬💰", "Quantum Thieves💻🕵️‍♂️", "Space Nomad Raiders🚀🏴‍☠️", "Cyberspace Intruders💻👾", "Anti-Transhumanist Factions🚫🦾", "Rogue Nanotech Swarms🔬🦠"],
    "👽 Terrorists": ["Bioengineered Virus Spreaders🧬💉", "Nanotechnology Saboteurs🔬🧨", "Cyber Terrorist Networks💻🔥", "Rogue AI Sects🤖🛑", "Space Anarchist Cells🚀Ⓐ", "Quantum Data Hijackers💻🔓", "Environmental Extremists🌍💣", "Technological Singularity Cults🤖🙏", "Interspecies Supremacists👽👑", "Orbital Bombardment Threats🛰️💥"],
}


# Function to search glossary and display results
def search_glossary(query):
    for category, terms in transhuman_glossary.items():
        if query.lower() in (term.lower() for term in terms):
            st.markdown(f"### {category}")
            st.write(f"- {query}")

# Display instructions and handle query parameters
st.markdown("## Glossary Lookup\nEnter a term in the URL query, like `?q=Nanotechnology` or `?query=Martian Syndicate`.")
query_params = st.query_params
query = (query_params.get('q') or query_params.get('query') or [''])[0]
if query: search_glossary(query)

    
            
# Display the glossary with Streamlit components, ensuring emojis are used
def display_glossary(area):
    st.subheader(f"📘 Glossary for {area}")
    terms = transhuman_glossary[area]
    for idx, term in enumerate(terms, start=1):
        st.write(f"{idx}. {term}")


# Function to display glossary in a 3x3 grid
def display_glossary_grid(glossary):
    # Group related categories for a 3x3 grid
    groupings = [
        ["🚀 Core Technologies", "🌐 Nations", "💡 Memes"],
        ["🏛 Institutions", "🔗 Organizations", "⚔️ War"],
        ["🎖 Military", "🦹 Outlaws", "👽 Terrorists"],
    ]
    
    for group in groupings:
        cols = st.columns(3)  # Create three columns
        for idx, category in enumerate(group):
            with cols[idx]:
                st.markdown(f"### {category}")
                terms = glossary[category]
                for term in terms:
                    st.write(f"- {term}")

# Display the glossary grid
st.title("Transhuman Space Glossary 🌌")
display_glossary_grid(transhuman_glossary)
        
# Streamlined UI for displaying buttons with scores, integrating emojis
def display_buttons_with_scores():
    for header, terms in transhuman_glossary.items():
        st.markdown(f"## {header}")
        for term in terms:
            key = generate_key(term, header, terms.index(term))
            score = load_score(key)
            if st.button(f"{term} {score}🚀", key=key):
                update_score(key)
                st.experimental_rerun()

if __name__ == "__main__":
    st.title("🌌🚀 Transhuman Space Encyclopedia")
    st.markdown("## Explore the universe of Transhuman Space through interactive storytelling and encyclopedic knowledge.🌠")
    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()

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

def clear_query_params():
    st.query_params()  

# Assuming the transhuman_glossary and other setup code remains the same

# Function to display content or image based on a query
def display_content_or_image(query):
    # Check if the query matches any glossary term
    for category, terms in transhuman_glossary.items():
        for term in terms:
            if query.lower() in term.lower():
                st.subheader(f"Found in {category}:")
                st.write(term)
                return True  # Return after finding and displaying the first match
    
    # Check for an image match in a predefined directory (adjust path as needed)
    image_dir = "images"  # Example directory where images are stored
    image_path = f"{image_dir}/{query}.png"  # Construct image path with query
    if os.path.exists(image_path):
        st.image(image_path, caption=f"Image for {query}")
        return True
    
    # If no content or image is found
    st.warning("No matching content or image found.")
    return False



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

# 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")

    
    

if 'query' in st.query_params:
    query = st.query_params['query'][0]  # Get the query parameter
    # Display content or image based on the query
    display_content_or_image(query)

# Add a clear query parameters button for convenience
if st.button("Clear Query Parameters", key='ClearQueryParams'):
    # This will clear the browser URL's query parameters
    st.experimental_set_query_params
    st.experimental_rerun()