"""
MLL Intake Assistant - PRODUCTION-GRADE Streamlit UI
====================================================
INDUSTRY-STANDARD FEATURES:
1. Professional appearance matching top enterprise chatbots
2. Clickable option buttons for selections
3. Real-time decision analysis panel
4. Interactive field collection
5. Progress tracking
6. Session persistence

VERSION: 2.0.0 - ENTERPRISE GRADE
"""

import streamlit as st
import uuid
import sys
from pathlib import Path
from datetime import datetime
import json
import os

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))

from config import settings
from orchestrator import orchestrator, initialize_system, process_message, create_session
from utils.data_loader import data_loader
from models.schemas import CapabilityCenter
from loguru import logger

# Create logs directory
os.makedirs("logs", exist_ok=True)
logger.add("logs/app.log", rotation="10 MB", level="INFO")

# Page configuration - MUST be first Streamlit command
st.set_page_config(
    page_title="MLL Intake Assistant",
    page_icon="🏭",
    layout="wide",
    initial_sidebar_state="expanded"
)

# ============================================================================
# PROFESSIONAL CSS STYLING - ENTERPRISE GRADE
# ============================================================================

st.markdown("""
<style>
    /* Global Styles */
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
    
    .main .block-container {
        padding: 1rem 2rem;
        max-width: 1400px;
    }
    
    /* Header */
    .main-header {
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
        color: white;
        padding: 1.5rem 2rem;
        border-radius: 12px;
        margin-bottom: 1.5rem;
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .main-header h1 {
        margin: 0;
        font-size: 1.8rem;
        font-weight: 700;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .main-header p {
        margin: 0.5rem 0 0 0;
        opacity: 0.85;
        font-size: 0.95rem;
    }
    
    /* Chat Container */
    .chat-container {
        background: #ffffff;
        border-radius: 12px;
        padding: 1rem;
        margin-bottom: 1rem;
        border: 1px solid #e0e0e0;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    /* Message Styles */
    .user-message {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 1rem 1.25rem;
        border-radius: 18px 18px 4px 18px;
        margin: 0.75rem 0;
        margin-left: 15%;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
    }
    
    .assistant-message {
        background: #f8f9fa;
        color: #1a1a2e;
        padding: 1rem 1.25rem;
        border-radius: 18px 18px 18px 4px;
        margin: 0.75rem 0;
        margin-right: 15%;
        border: 1px solid #e9ecef;
        box-shadow: 0 2px 8px rgba(0,0,0,0.03);
    }
    
    /* Option Buttons */
    .option-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 0.75rem;
        margin: 1rem 0;
    }
    
    .option-button {
        background: white;
        border: 2px solid #e0e0e0;
        border-radius: 10px;
        padding: 1rem;
        cursor: pointer;
        transition: all 0.2s ease;
        text-align: left;
    }
    
    .option-button:hover {
        border-color: #667eea;
        background: #f8f9ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
    }
    
    .option-button.selected {
        border-color: #667eea;
        background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
    }
    
    /* Progress Bar */
    .progress-container {
        background: #e9ecef;
        border-radius: 10px;
        height: 8px;
        margin: 1rem 0;
        overflow: hidden;
    }
    
    .progress-bar {
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        height: 100%;
        border-radius: 10px;
        transition: width 0.5s ease;
    }
    
    /* Sidebar Styles */
    .sidebar-card {
        background: white;
        border-radius: 10px;
        padding: 1rem;
        margin-bottom: 1rem;
        border: 1px solid #e0e0e0;
    }
    
    .sidebar-title {
        font-weight: 600;
        color: #1a1a2e;
        margin-bottom: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    /* Quick Action Buttons */
    .stButton > button {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 8px;
        padding: 0.5rem 1rem;
        font-weight: 500;
        transition: all 0.2s ease;
    }
    
    .stButton > button:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }
    
    /* Analysis Panel */
    .analysis-panel {
        background: #1a1a2e;
        color: #a0aec0;
        border-radius: 10px;
        padding: 1rem;
        font-family: 'Courier New', monospace;
        font-size: 0.85rem;
        margin-top: 1rem;
    }
    
    .analysis-panel .step {
        padding: 0.25rem 0;
        border-bottom: 1px solid #2d3748;
    }
    
    .analysis-panel .step:last-child {
        border-bottom: none;
    }
    
    /* Field Status */
    .field-complete {
        color: #48bb78;
    }
    
    .field-pending {
        color: #ed8936;
    }
    
    /* Hide Streamlit Defaults */
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    .stDeployButton {display: none;}
    
    /* Selection Tables */
    .selection-table {
        width: 100%;
        border-collapse: collapse;
        margin: 1rem 0;
    }
    
    .selection-table th {
        background: #1a1a2e;
        color: white;
        padding: 0.75rem;
        text-align: left;
    }
    
    .selection-table td {
        padding: 0.75rem;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .selection-table tr:hover {
        background: #f8f9ff;
    }
</style>
""", unsafe_allow_html=True)


# ============================================================================
# SESSION STATE INITIALIZATION
# ============================================================================

def init_session_state():
    """Initialize all session state variables"""
    defaults = {
        'session_id': str(uuid.uuid4()),
        'messages': [],
        'system_initialized': False,
        'show_debug': False,
        'collected_fields': {},
        'pending_message': None,
        'current_options': None,
        'analysis_log': [],
        'show_analysis': False
    }
    
    for key, value in defaults.items():
        if key not in st.session_state:
            st.session_state[key] = value


def init_system():
    """Initialize the backend system"""
    if not st.session_state.system_initialized:
        with st.spinner("🔧 Initializing MLL Intake Assistant..."):
            try:
                success = initialize_system()
                st.session_state.system_initialized = success
                if success:
                    logger.info("System initialized successfully")
            except Exception as e:
                logger.error(f"Initialization error: {e}")
                st.session_state.system_initialized = False


# ============================================================================
# MAIN RENDER FUNCTIONS
# ============================================================================

def render_header():
    """Render professional header"""
    st.markdown("""
    <div class="main-header">
        <h1>🏭 MLL Intake Assistant</h1>
        <p>Enterprise Multi-Agent AI Chatbot for IT Service Requests</p>
    </div>
    """, unsafe_allow_html=True)


def render_sidebar():
    """Render enhanced sidebar"""
    with st.sidebar:
        # Logo and Title
        st.markdown("## 🏭 MLL Intake")
        st.caption("v2.0 Production")
        
        st.divider()
        
        # System Status
        st.markdown("### 📊 System Status")
        if st.session_state.system_initialized:
            st.success("✅ System Online")
            stats = data_loader.get_statistics()
            col1, col2 = st.columns(2)
            with col1:
                st.metric("IRIS", f"{stats.get('iris_count', 0):,}")
            with col2:
                st.metric("Epics", f"{stats.get('epics_count', 0):,}")
        else:
            st.warning("⏳ Initializing...")
        
        st.divider()
        
        # Quick Actions with Icons
        st.markdown("### ⚡ Quick Actions")
        
        col1, col2 = st.columns(2)
        with col1:
            if st.button("🆕 New Intake", use_container_width=True, key="btn_intake"):
                st.session_state.pending_message = "I need to submit a new Solution Intake request"
            if st.button("🌐 Network", use_container_width=True, key="btn_network"):
                st.session_state.pending_message = "I need to submit a network/firewall request"
            if st.button("📋 Status", use_container_width=True, key="btn_status"):
                st.session_state.pending_message = "I want to check the status of my request"
        
        with col2:
            if st.button("🔴 Incident", use_container_width=True, key="btn_incident"):
                st.session_state.pending_message = "I need to report an incident"
            if st.button("🔑 Access", use_container_width=True, key="btn_access"):
                st.session_state.pending_message = "I need access to TS ENGAGE-PROD"
            if st.button("❓ Help", use_container_width=True, key="btn_help"):
                st.session_state.pending_message = "Can you explain the intake process?"
        
        st.divider()
        
        # Session Info with Visual Progress
        st.markdown("### 📝 Current Session")
        st.text(f"ID: {st.session_state.session_id[:8]}...")
        st.text(f"Messages: {len(st.session_state.messages)}")
        
        # Collected Fields Display
        if st.session_state.collected_fields:
            st.markdown("**Collected Fields:**")
            for key, value in st.session_state.collected_fields.items():
                if not key.startswith('_'):
                    val_str = str(value)
                    if hasattr(value, 'value'):
                        val_str = value.value
                    st.markdown(f"✅ **{key}**: {val_str[:25]}{'...' if len(val_str) > 25 else ''}")
        
        st.divider()
        
        # Controls
        st.markdown("### ⚙️ Controls")
        
        if st.button("🗑️ Clear Chat", use_container_width=True):
            clear_conversation()
            st.rerun()
        
        st.session_state.show_analysis = st.checkbox(
            "🔍 Show Decision Analysis", 
            value=st.session_state.show_analysis
        )
        
        st.divider()
        
        # About
        with st.expander("📚 About"):
            st.markdown("""
            **MLL Intake Assistant** v2.0
            
            **Capabilities:**
            - Solution Intake Requests
            - Network/Firewall Requests
            - Incident Reporting
            - Access Requests
            - Status Tracking
            
            **Powered by:**
            - 8 Specialized AI Agents
            - Semantic Classification
            - 16,000+ Historical Records
            """)


def render_welcome():
    """Render welcome screen when no messages"""
    if not st.session_state.messages:
        st.markdown("""
        <div style="text-align: center; padding: 3rem 2rem; 
                    background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
                    border-radius: 16px; margin: 2rem 0;">
            <h2 style="color: #1a1a2e; margin-bottom: 0.5rem;">
                👋 Welcome to MLL Intake Assistant
            </h2>
            <p style="color: #4a5568; font-size: 1.1rem;">
                I'm here to help you submit IT service requests for Manufacturing, Logistics & Labs.
            </p>
        </div>
        """, unsafe_allow_html=True)
        
        # Feature cards
        cols = st.columns(3)
        with cols[0]:
            st.markdown("""
            <div style="background: white; padding: 1.5rem; border-radius: 12px; 
                        border: 1px solid #e0e0e0; text-align: center; height: 180px;">
                <div style="font-size: 2.5rem; margin-bottom: 0.5rem;">🆕</div>
                <h4 style="margin: 0; color: #1a1a2e;">Solution Intake</h4>
                <p style="color: #718096; font-size: 0.9rem; margin-top: 0.5rem;">
                    Submit new IT service requests
                </p>
            </div>
            """, unsafe_allow_html=True)
        
        with cols[1]:
            st.markdown("""
            <div style="background: white; padding: 1.5rem; border-radius: 12px; 
                        border: 1px solid #e0e0e0; text-align: center; height: 180px;">
                <div style="font-size: 2.5rem; margin-bottom: 0.5rem;">🔴</div>
                <h4 style="margin: 0; color: #1a1a2e;">Report Issues</h4>
                <p style="color: #718096; font-size: 0.9rem; margin-top: 0.5rem;">
                    Report incidents when something stops working
                </p>
            </div>
            """, unsafe_allow_html=True)
        
        with cols[2]:
            st.markdown("""
            <div style="background: white; padding: 1.5rem; border-radius: 12px; 
                        border: 1px solid #e0e0e0; text-align: center; height: 180px;">
                <div style="font-size: 2.5rem; margin-bottom: 0.5rem;">📋</div>
                <h4 style="margin: 0; color: #1a1a2e;">Track Status</h4>
                <p style="color: #718096; font-size: 0.9rem; margin-top: 0.5rem;">
                    Check status of your RITM or Jira tickets
                </p>
            </div>
            """, unsafe_allow_html=True)
        
        st.markdown("---")
        st.markdown("**💬 Type your question below or use Quick Actions in the sidebar!**")


def render_chat():
    """Render chat messages with professional styling"""
    for msg in st.session_state.messages:
        if msg["role"] == "user":
            with st.chat_message("user", avatar="👤"):
                st.markdown(msg["content"])
        else:
            with st.chat_message("assistant", avatar="🤖"):
                st.markdown(msg["content"])
                
                # Show analysis if enabled and available
                if st.session_state.show_analysis and "_analysis" in msg:
                    with st.expander("🔍 View Decision Analysis"):
                        st.code(msg["_analysis"], language=None)


def render_interactive_options(response: str):
    """
    Detect if response contains options and render as clickable buttons
    """
    # Check for capability center selection
    if "SELECT CAPABILITY CENTER" in response or "Which Capability Center" in response:
        st.markdown("**Quick Select:**")
        cols = st.columns(4)
        options = [
            ("1️⃣ Agile Demand", "1"),
            ("2️⃣ Approved Project", "2"),
            ("3️⃣ Estimate", "3"),
            ("4️⃣ TS Internal", "4")
        ]
        for i, (label, value) in enumerate(options):
            with cols[i]:
                if st.button(label, key=f"cap_opt_{value}_{datetime.now().timestamp()}"):
                    st.session_state.pending_message = value
                    st.rerun()
    
    # Check for site selection
    elif "SELECT YOUR SITE" in response or "What site is this request for" in response:
        st.markdown("**Quick Select Site:**")
        cols = st.columns(3)
        sites = [
            ("🏭 JUAREZ (6749)", "6749"),
            ("🏭 JACKSONVILLE (6750)", "6750"),
            ("🏭 LIMERICK (6751)", "6751"),
            ("🏭 GURABO (6752)", "6752"),
            ("🏭 LEEDS (6753)", "6753"),
            ("🏭 ATHENS (6754)", "6754")
        ]
        for i, (label, value) in enumerate(sites):
            with cols[i % 3]:
                if st.button(label, key=f"site_opt_{value}_{datetime.now().timestamp()}"):
                    st.session_state.pending_message = value
                    st.rerun()
    
    # Check for confirmation
    elif "confirm" in response.lower() and "submit" in response.lower():
        cols = st.columns(2)
        with cols[0]:
            if st.button("✅ Confirm & Submit", type="primary", key=f"confirm_{datetime.now().timestamp()}"):
                st.session_state.pending_message = "confirm"
                st.rerun()
        with cols[1]:
            if st.button("✏️ Make Changes", key=f"edit_{datetime.now().timestamp()}"):
                st.session_state.pending_message = "I want to make changes"
                st.rerun()


def process_user_input(user_input: str):
    """Process user input through the orchestrator"""
    if not user_input or not user_input.strip():
        return
    
    # Add user message
    st.session_state.messages.append({
        "role": "user",
        "content": user_input,
        "timestamp": datetime.now().isoformat()
    })
    
    # Get response
    with st.spinner("🤔 Processing..."):
        try:
            response = process_message(st.session_state.session_id, user_input)
            
            # Update collected fields
            session_state = orchestrator.get_session(st.session_state.session_id)
            if session_state:
                st.session_state.collected_fields = session_state.collected_fields.copy()
                
                # Get analysis if available
                analysis = session_state.collected_fields.get('_analysis', '')
            else:
                analysis = ''
            
            # Add assistant message
            st.session_state.messages.append({
                "role": "assistant",
                "content": response,
                "timestamp": datetime.now().isoformat(),
                "_analysis": analysis
            })
            
        except Exception as e:
            logger.error(f"Error processing: {e}")
            st.session_state.messages.append({
                "role": "assistant",
                "content": f"I apologize, but I encountered an error. Please try again.",
                "timestamp": datetime.now().isoformat()
            })


def clear_conversation():
    """Clear conversation and reset state"""
    st.session_state.messages = []
    st.session_state.session_id = str(uuid.uuid4())
    st.session_state.collected_fields = {}
    st.session_state.pending_message = None
    orchestrator.clear_session(st.session_state.session_id)
    logger.info("Conversation cleared")


# ============================================================================
# MAIN APP
# ============================================================================

def main():
    """Main application entry point"""
    # Initialize
    init_session_state()
    init_system()
    
    # Render UI
    render_sidebar()
    render_header()
    
    # Handle pending messages from quick actions
    if st.session_state.pending_message:
        process_user_input(st.session_state.pending_message)
        st.session_state.pending_message = None
        st.rerun()
    
    # Main content
    render_welcome()
    render_chat()
    
    # Show interactive options for last message
    if st.session_state.messages and st.session_state.messages[-1]["role"] == "assistant":
        render_interactive_options(st.session_state.messages[-1]["content"])
    
    # Chat input
    if prompt := st.chat_input("Type your message here...", key="chat_input"):
        process_user_input(prompt)
        st.rerun()


if __name__ == "__main__":
    main()
