from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from contextlib import asynccontextmanager import uvicorn import logging from adapters.sqlite.database import init_db from routers import entities, export, data, amocrm from utils.config import settings # FastStream integration from faststream.redis.fastapi import RedisRouter from workers.broker import broker from workers.middleware import setup_middleware # Configure logging logging.basicConfig(level=settings.LOG_LEVEL) logger = logging.getLogger(__name__) # Setup FastStream middleware setup_middleware(broker) # Create FastStream router for FastAPI integration redis_router = RedisRouter(broker) @asynccontextmanager async def lifespan(app: FastAPI): # Startup logger.info("Starting AMO CRM Data Collection Service") await init_db() logger.info("Database initialized successfully") yield # Shutdown logger.info("Shutting down AMO CRM Data Collection Service") app = FastAPI( title="AMO CRM Data Collection Service", description="Service for collecting and exporting AMO CRM data to Google Sheets with FastStream workers", version="0.1.0", lifespan=redis_router.lifespan_context, ) # CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Configure appropriately for production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include FastStream router for message handling app.include_router(redis_router) # Include API routers app.include_router(entities.router, prefix=f"{settings.API_V1_STR}/entities", tags=["entities"]) app.include_router(export.router, prefix=f"{settings.API_V1_STR}/export", tags=["export"]) app.include_router(data.router, prefix=f"{settings.API_V1_STR}/data", tags=["data"]) app.include_router(amocrm.router, prefix=f"{settings.API_V1_STR}/amocrm", tags=["amocrm"]) @app.get("/") async def root() -> dict[str, str]: return {"message": "AMO CRM Data Collection Service", "version": "0.1.0"} @app.get("/health") async def health_check() -> dict[str, str]: return {"status": "healthy"} if __name__ == "__main__": uvicorn.run( "app:app", host="0.0.0.0", port=8000, reload=True, log_level=settings.LOG_LEVEL.lower(), )