import uvicorn
import signal
import sys
from src.shared.config.settings import settings
from src.shared.config.logging_config import setup_logging, get_logger
setup_logging()
logger = get_logger(__name__)

def signal_handler(sig, frame):
    """Handle Ctrl+C gracefully."""
    logger.info('\nReceived interrupt signal (Ctrl+C). Shutting down gracefully...')
    sys.exit(0)

if __name__ == '__main__':
    # Register signal handler for graceful shutdown on Ctrl+C
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    logger.info(f'Starting {settings.APP_NAME} on {settings.HOST}:{settings.PORT}')
    import os
    from pathlib import Path
    base_dir = Path(__file__).parent
    src_dir = str(base_dir / 'src')
    # Enable hot reload in development mode or if explicitly enabled via environment variable
    use_reload = settings.is_development or os.getenv('ENABLE_RELOAD', 'false').lower() == 'true'
    if use_reload:
        logger.info('Hot reload enabled - server will restart on code changes')
        logger.info('Press Ctrl+C to stop the server')
    uvicorn.run(
        'src.main:app',
        host=settings.HOST,
        port=settings.PORT,
        reload=use_reload,
        log_level=settings.LOG_LEVEL.lower(),
        reload_dirs=[src_dir] if use_reload else None,
        reload_excludes=['*.log', '*.pyc', '*.pyo', '*.pyd', '__pycache__', '**/__pycache__/**', '*.db', '*.sqlite', '*.sqlite3', 'venv/**', '.venv/**'],
        reload_delay=0.5
    )