#!/usr/bin/env python3
import os
import sys
import importlib

def main():
    component = os.getenv('COMPONENT_NAME', 'eveai_app')
    role = os.getenv('ROLE', 'web')
    
    if role == 'web':
        # Web services
        from gevent import monkey
        monkey.patch_all()
        
        try:
            module = importlib.import_module(component)
            app = module.create_app()
            
        except ImportError as e:
            print(f"Error importing {component}: {e}", file=sys.stderr)
            sys.exit(1)
        except AttributeError as e:
            print(f"Error: {component} module does not have create_app function: {e}", file=sys.stderr)
            sys.exit(1)
    
    elif role in ['worker', 'beat']:
        # Worker services
        try:
            module = importlib.import_module(component)
            celery = module.celery
            
        except ImportError as e:
            print(f"Error importing {component}: {e}", file=sys.stderr)
            sys.exit(1)
        except AttributeError as e:
            print(f"Error: {component} module does not have celery object: {e}", file=sys.stderr)
            sys.exit(1)
    
    else:
        print(f"Unknown role: {role}", file=sys.stderr)
        sys.exit(1)

# For web services - expose app object for gunicorn
if os.getenv('ROLE', 'web') == 'web':
    component = os.getenv('COMPONENT_NAME', 'eveai_app')
    try:
        from gevent import monkey
        monkey.patch_all()
        
        module = importlib.import_module(component)
        app = module.create_app()
    except (ImportError, AttributeError) as e:
        print(f"Error setting up app for {component}: {e}", file=sys.stderr)
        app = None

# For worker/beat services - expose celery object
elif os.getenv('ROLE') in ['worker', 'beat']:
    component = os.getenv('COMPONENT_NAME', 'eveai_workers')
    try:
        module = importlib.import_module(component)
        celery = module.celery
    except (ImportError, AttributeError) as e:
        print(f"Error setting up celery for {component}: {e}", file=sys.stderr)
        celery = None

if __name__ == '__main__':
    main()