import streamlit as st
import requests
import os
import pandas as pd

BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:8000")

st.set_page_config(page_title="Lectures", page_icon="🗂️")

st.title("🗂️ Data from Backend")

# try:
#     response = requests.get(f"{BACKEND_URL}/api/lectures/")
#     if response.status_code == 200:
#         st.json(response.json())
#     else:
#         st.error(f"Error {response.status_code}: {response.text}")
# except Exception as e:
#     st.error(f"Failed to connect to backend: {e}")

# Get JSON from backend
try:
    response = requests.get(f"{BACKEND_URL}/api/lectures")
    if response.status_code == 200:
        data = response.json()

        # Switch: JSON view or Table view
        view_mode = st.radio("Select view:", ["JSON", "Table"], horizontal=True)

        if view_mode == "JSON":
            st.subheader("Raw JSON")
            st.json(data)

        elif view_mode == "Table":
            st.subheader("Tabular view")

            # Convert JSON to table (assuming list of dicts or dict-like)
            if isinstance(data["response"]["data"]["lectures"], list):
                df = pd.DataFrame(data["response"]["data"]["lectures"])
            elif isinstance(data["response"]["data"]["lectures"], dict):
                # when backend returns dict, wrap it
                df = pd.DataFrame([data["response"]["data"]["lectures"]])
            else:
                st.error("Unsupported JSON format for table view.")
                df = None

            if df is not None:
                st.dataframe(df, use_container_width=True)

    else:
        st.error(f"Error {response.status_code}: {response.text}")

except Exception as e:
    st.error(f"Failed to connect to backend: {e}")