"""
IGF Admin - MongoDB Data Management UI

A Streamlit-based admin interface for managing IGF data in MongoDB.

Key principles:
- MongoDB is the single source of truth
- All operations are manual (user-initiated)
- No automatic imports or data modifications
- Excel-like data management interface
"""

import streamlit as st
import yaml
from pathlib import Path
from services.mongo import MongoService
from services.data_service import DataService
from services.schema_manager import SchemaManager
from services.settings_service import SettingsService
from ui.tabs.json_vs_db import render_json_vs_db_tab
from ui.tabs.settings import render_settings_tab
from ui.tabs.relationships import render_relationships_tab


def load_config():
    """Load application configuration from YAML file."""
    config_path = Path(__file__).parent / "config" / "app_config.yaml"
    with open(config_path, 'r') as f:
        return yaml.safe_load(f)


# Load configuration
config = load_config()

# Page configuration from config
st.set_page_config(
    page_title=config['ui']['app_title'],
    page_icon=config['ui']['app_icon'],
    layout="wide",
    initial_sidebar_state="expanded"
)


def init_services(config):
    """
    Initialize MongoDB and data services and store in session state.
    
    Args:
        config: Application configuration dictionary
    
    This ensures we maintain a single connection throughout the session.
    """
    # Store config in session state
    if 'config' not in st.session_state:
        st.session_state.config = config
    
    if 'mongo_service' not in st.session_state:
        st.session_state.mongo_service = MongoService()
        st.session_state.mongo_service.connect()
    
    if 'data_service' not in st.session_state:
        st.session_state.data_service = DataService(st.session_state.mongo_service)
    
    if 'schema_manager' not in st.session_state:
        st.session_state.schema_manager = SchemaManager(st.session_state.mongo_service)
    
    if 'settings_service' not in st.session_state:
        st.session_state.settings_service = SettingsService()
    
    # Initialize selected page
    if 'selected_page' not in st.session_state:
        st.session_state.selected_page = 'home'


def render_sidebar(config):
    """
    Render the sidebar with project info, navigation, and collection list.
    
    Args:
        config: Application configuration dictionary
    """
    with st.sidebar:
        st.title(f"{config['ui']['app_icon']} {config['ui']['app_title']}")
        st.markdown("---")
        
        # MongoDB connection status
        st.subheader("📊 Database Status")
        
        mongo = st.session_state.mongo_service
        
        if mongo.is_connected():
            st.success("✅ Connected")
            st.info(f"**Database:** {mongo.get_database_name()}")
        else:
            st.error("❌ Not Connected")
            error = mongo.get_connection_error()
            if error:
                st.error(f"Error: {error}")
            
            if st.button("🔄 Retry Connection"):
                mongo.connect()
                st.rerun()
        
        st.markdown("---")
        
        # Navigation
        st.subheader("🧭 Navigation")
        
        # Build page options based on feature flags
        page_options = {'home': '🏠 Home'}
        
        if config['ui'].get('enable_json_vs_db', True):
            page_options['json_vs_db'] = '🔄 JSON vs DB'
        
        page_options['relationships'] = '🔗 Relationships'
        page_options['settings'] = '⚙️ Settings'
        
        selected_page = st.radio(
            "Select page:",
            options=list(page_options.keys()),
            format_func=lambda x: page_options[x],
            key="page_selector"
        )
        
        st.session_state.selected_page = selected_page
        
        st.markdown("---")
        
        # Show collection stats in expandable section
        collections = mongo.list_collections()
        if collections:
            with st.expander("📊 Collection Statistics", expanded=False):
                for collection in collections:
                    count = mongo.count_documents(collection)
                    st.text(f"• {collection}: {count:,}")
        
        st.markdown("---")
        
        # Footer
        st.caption(f"{config['ui']['app_title']} v{config['ui']['app_version']}")
        st.caption(config['ui']['app_tagline'])


def render_welcome_screen():
    """
    Render the main welcome screen with collection overview.
    """
    st.title("Welcome to IGF Admin")
    st.markdown("""
    This is a manual data management interface for the IGF MongoDB database.
    
    **Key Features:**
    - 🔄 **JSON vs DB:** Compare and import data from JSON files
    - ⚙️ **Settings:** Configure MongoDB connection through the UI
    - 📊 View collection statistics and database status
    - 📝 Manual data entry and updates
    - 🚫 No automatic imports or modifications
    
    **Important:**
    - MongoDB is the single source of truth
    - All changes are manual and user-controlled
    - No data is automatically merged or modified
    """)
    
    st.markdown("---")
    
    # Collection statistics
    st.subheader("📊 Collection Overview")
    
    mongo = st.session_state.mongo_service
    
    if not mongo.is_connected():
        st.warning("⚠️ Not connected to MongoDB. Please check the sidebar for connection status.")
        return
    
    st.markdown("---")
    
    # Next steps
    st.info("""
    **Getting Started:**
    
    1. **Check Connection:** Verify MongoDB connection status in the sidebar
    2. **Configure Settings:** Use ⚙️ Settings to update MongoDB connection if needed
    3. **Import Data:** Use 🔄 JSON vs DB to compare and import data from JSON files
    4. **Monitor Collections:** View collection statistics above
    
    All operations are manual and require explicit user confirmation.
    """)


def main():
    """
    Main application entry point.
    """
    # Initialize services with config
    init_services(config)
    
    # Render sidebar with config
    render_sidebar(config)
    
    # Render main content based on page selection
    selected_page = st.session_state.selected_page
    
    if selected_page == 'home':
        # Show welcome screen
        render_welcome_screen()
    
    elif selected_page == 'json_vs_db':
        # Show JSON vs DB comparison tab
        if config['ui'].get('enable_json_vs_db', True):
            render_json_vs_db_tab(
                st.session_state.mongo_service,
                st.session_state.data_service,
                config,
                st.session_state.settings_service
            )
        else:
            st.warning("JSON vs DB feature is disabled in configuration")
    
    elif selected_page == 'relationships':
        # Show relationships tab
        render_relationships_tab(
            st.session_state.mongo_service,
            config
        )
    
    elif selected_page == 'settings':
        # Show settings tab
        render_settings_tab(
            st.session_state.settings_service,
            st.session_state.mongo_service
        )


if __name__ == "__main__":
    main()
