"""
Enhanced Server Monitoring System v2.0
Main application entry point

This is the main file to start the enhanced server monitoring system.
It includes all the improvements requested:
- Better database structure with message compression
- File upload support
- SSH/Ansible management interface
- Modular architecture
- Smaller client message sizes through templates
"""

import os
import sys
from app import create_app
from config.database_config import get_db

def main():
    """Main application entry point"""
    
    # Create application
    app = create_app()
    
    # Setup database if needed (after app creation to avoid circular imports)
    with app.app_context():
        from config.database_config import get_db
        db = get_db()
        if not os.path.exists('data/enhanced_monitoring.db'):
            print("🔧 Setting up database for first time...")
            success = db.create_tables()
            if success:
                print("✅ Database initialized successfully")
            else:
                print("❌ Database initialization failed")
                return 1
        else:
            # Existing database – make sure any newly added columns are present
            db.ensure_schema()
        
        # Create initial dummy data if database is empty (for testing)
        create_sample_data_if_needed()
    
    # Print startup information
    print_startup_info()
    
    # Run application
    try:
        app.run(
            host='0.0.0.0',
            port=int(os.environ.get('PORT', 80)),
            debug=app.config.get('DEBUG', False)
        )
    except KeyboardInterrupt:
        print("\n👋 Shutting down Enhanced Server Monitoring System")
        return 0
    except Exception as e:
        print(f"❌ Failed to start server: {e}")
        return 1

def create_sample_data_if_needed():
    """Create sample data for testing if database is empty"""
    try:
        from config.database_config import get_db
        from app.models import Device, MessageTemplate
        
        db = get_db()
        with db.get_session() as session:
            # Check if we have any devices
            device_count = session.query(Device).count()
            
            if device_count == 0:
                print("📝 Creating sample data for testing...")
                
                # Create sample devices
                sample_devices = [
                    Device(
                        hostname='rpi-device-01',
                        device_ip='192.168.1.100',
                        nume_masa='Masa-01',
                        device_type='Raspberry Pi',
                        status='active',
                        location='Office Floor 1'
                    ),
                    Device(
                        hostname='rpi-device-02', 
                        device_ip='192.168.1.101',
                        nume_masa='Masa-02',
                        device_type='Raspberry Pi',
                        status='active',
                        location='Office Floor 2'
                    )
                ]
                
                for device in sample_devices:
                    session.add(device)
                
                # Create sample message templates
                sample_templates = [
                    MessageTemplate(
                        template_hash='sample1',
                        template_text='Card detected: {card_id}',
                        category='card_detection',
                        alias='CD001'
                    ),
                    MessageTemplate(
                        template_hash='sample2',
                        template_text='System startup completed in {time}s',
                        category='system_startup', 
                        alias='SS001'
                    )
                ]
                
                for template in sample_templates:
                    session.add(template)
                
                session.commit()
                print("✅ Sample data created successfully")
                
    except Exception as e:
        print(f"⚠️  Warning: Could not create sample data: {e}")

def print_startup_info():
    """Print startup information and available endpoints"""
    
    print("\n" + "="*60)
    print("🚀 ENHANCED SERVER MONITORING SYSTEM v2.0")
    print("="*60)
    print("\n📊 Enhanced Features:")
    print("   • Message compression and aliasing")
    print("   • File upload support")
    print("   • SSH/Ansible management interface") 
    print("   • Improved database structure")
    print("   • Modular architecture")
    print("   • Real-time device monitoring")
    
    print("\n🌐 API Endpoints:")
    print("   • POST /api/logs/                     - Submit compressed logs")
    print("   • POST /api/logs/template/<alias>     - Submit using template alias")
    print("   • POST /api/logs/file                 - Upload log files")
    print("   • GET  /api/logs/query                - Query logs with filters")
    print("   • GET  /api/logs/stats                - Get compression statistics")
    print("   • GET  /api/logs/templates            - View message templates")
    
    print("\n🔧 Ansible Management:")
    print("   • GET  /api/ansible/inventory         - View device inventory")
    print("   • POST /api/ansible/execute           - Execute playbooks")
    print("   • GET  /api/ansible/executions        - View execution history") 
    print("   • POST /api/ansible/ssh/test          - Test SSH connectivity")
    
    print("\n💻 Web Interface:")
    print("   • /                                   - Enhanced dashboard")
    print("   • /devices                            - Device management")
    print("   • /logs                               - Log viewer with filters")
    print("   • /templates                          - Message template manager")
    print("   • /ansible/                           - Ansible management dashboard")
    print("   • /ansible/execute                    - Execute playbooks via web")
    print("   • /ansible/ssh/setup                  - SSH key management")
    
    print("\n🔗 Integration with Prezenta App:")
    print("   • Prezenta devices can now send smaller messages using template aliases")
    print("   • Example: Instead of 'Card detected: ABC123', send alias 'CD001' + variables")
    print("   • 60-80% reduction in message size for common log patterns")
    
    print("\n💾 Database Improvements:")
    print("   • Normalized schema with separate device/log/template tables")
    print("   • Message deduplication and compression")
    print("   • File upload tracking and metadata")
    print("   • Ansible execution history")
    print("   • System statistics and metrics")
    
    print(f"\n🔧 Quick Setup for Prezenta Clients:")
    print(f"   1. Update server URL to: http://YOUR-SERVER-IP/api/logs/")
    print(f"   2. Use new compressed message format")
    print(f"   3. Optional: Upload config files via /api/logs/file")
    
    print("\n" + "="*60)
    print("✅ Server ready! Access web interface at http://YOUR-IP/")
    print("="*60 + "\n")

if __name__ == '__main__':
    sys.exit(main())