# Run this file to test the Streamlit UI
#
# $ streamlit run tests/test_streamlit_demo.py
#
# If you get an error about the config file, run the following command to kill all running Streamlit processes:
#
# $ lsof -ti :8501 | xargs kill -9

import streamlit as st
import requests
from datetime import datetime
import time

def get_history_hash(history):
    """Get a hash of the history to detect changes"""
    return hash(str(history))

def main():
    st.title("WhisperChain Dashboard")
    
    # Initialize session state for history tracking
    if 'last_history_hash' not in st.session_state:
        st.session_state.last_history_hash = None
    
    # Server status check
    try:
        response = requests.get("http://localhost:8000")
        server_online = response.status_code == 200
    except:
        server_online = False

    # Display server status
    st.sidebar.header("Server Status")
    if server_online:
        st.sidebar.success("🟢 Server Online")
    else:
        st.sidebar.error("🔴 Server Offline")

    # Transcription History
    st.header("Transcription History")
    
    # Clear history button
    if st.button("Clear History"):
        requests.delete("http://localhost:8000/history")
        st.session_state.last_history_hash = None
        st.rerun()

    try:
        # Fetch history from server
        response = requests.get("http://localhost:8000/history")
        history = response.json()
        
        # Check if history has changed
        current_hash = get_history_hash(history)
        history_changed = current_hash != st.session_state.last_history_hash
        st.session_state.last_history_hash = current_hash
        
        # Display transcriptions
        for idx, entry in enumerate(reversed(history)):
            with st.expander(f"Transcription {len(history) - idx}", expanded=False):
                col1, col2 = st.columns(2)
                with col1:
                    st.subheader("Raw Transcription")
                    st.text(entry.get("transcription", ""))
                    st.caption(f"Processed bytes: {entry.get('processed_bytes', 0)}")
                with col2:
                    st.subheader("Cleaned Transcription")
                    st.text(entry.get("cleaned_transcription", ""))
                    st.caption(f"Timestamp: {entry.get('timestamp', '')}")
        
        # Only rerun if history has changed
        if history_changed:
            print("History changed, rerunning...")
            time.sleep(0.1)  # Small delay to prevent too frequent updates
            st.rerun()
        else:
            time.sleep(5)  # Longer delay when no changes
            st.rerun()
            
    except Exception as e:
        st.error(f"Error fetching history: {str(e)}")
        time.sleep(5)
        st.rerun()

if __name__ == "__main__":
    main() 