import streamlit as st
import requests
import json
import pprint

# Function to fetch data from Google Knowledge Graph
def fetch_data(query, api_key, limit):
    url = f"https://kgsearch.googleapis.com/v1/entities:search?query={query}&key={api_key}&limit={limit}"
    response = requests.get(url)
    json_data = json.loads(response.text)
    return json_data

# Streamlit UI
st.title('Google Knowledge Graph Search')

# Try to fetch API key from secrets.toml
api_key = st.secrets.get("gkg", {}).get("api_key") if isinstance(st.secrets.get("gkg", {}), dict) else None

# If not found, ask for it
if not api_key:
    api_key = st.text_input('Enter your Google API Key:', type="password")

search_query = st.text_input('Enter Search Query:', 'Python Programming')
output_count = st.slider('Number of Results:', min_value=1, max_value=10, value=1)

if st.button('Search'):
    if api_key:
        result = fetch_data(search_query, api_key, output_count)
        try:
            # Pretty-print the entire JSON response to display all outputs
            st.subheader("Full JSON Response")
            st.write(pprint.pformat(result))
        except:
            st.write('No results found.')
    else:
        st.write('API key is missing.')