#!/usr/bin/env python3
"""
MHA Flow Production Server
Quick start script for running the Flask application
"""
import os
import sys

# Add current directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def main():
    print("="*70)
    print("MHA Flow v3.0 - Production Server")
    print("="*70)
    
    # Check if database exists
    if not os.path.exists('mha_production.db'):
        database_url = os.environ.get('DATABASE_URL')
        if not database_url:
            print("\n⚠️  Database not found!")
            print("   Run: python init_db.py full")
            response = input("\n   Initialize database now? (y/n): ").lower()
            if response == 'y':
                from init_db import init_database, init_system_settings, create_admin_user, create_demo_user
                init_database()
                init_system_settings()
                create_admin_user()
                create_demo_user()
                print("\n✅ Database initialized!")
            else:
                print("\n❌ Cannot start without database. Exiting...")
                sys.exit(1)
    
    # Import app
    from app_production import app
    
    # Get configuration
    host = os.environ.get('HOST', '0.0.0.0')
    port = int(os.environ.get('PORT', 5000))
    debug = os.environ.get('DEBUG', 'True').lower() == 'true'
    
    print(f"\n🌐 Starting server on http://{host}:{port}")
    print(f"📊 Environment: {os.environ.get('FLASK_ENV', 'development')}")
    print(f"🐛 Debug mode: {debug}")
    
    if debug:
        print("\n⚠️  Debug mode is ON - only use in development!")
        print("   Set FLASK_ENV=production for production deployment")
    
    print("\n💡 Press Ctrl+C to stop the server")
    print("="*70 + "\n")
    
    # Run the app
    try:
        app.run(host=host, port=port, debug=debug)
    except KeyboardInterrupt:
        print("\n\n👋 Server stopped")
    except Exception as e:
        print(f"\n❌ Error: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()
