from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import structlog

from app.config import settings
from app.api.routes import documents, templates
from app.core.redis_client import redis_client
from app.core.logging import setup_logging

# Настройка логирования
setup_logging()
logger = structlog.get_logger()

# Создание FastAPI приложения
app = FastAPI(
    title="ERP Document Service",
    description="Сервис для генерации документов (PDF, Excel, Word)",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# Настройка CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Подключение роутов
app.include_router(documents.router, prefix="/api/documents", tags=["documents"])
app.include_router(templates.router, prefix="/api/templates", tags=["templates"])

@app.on_event("startup")
async def startup_event():
    """Событие запуска приложения"""
    logger.info("Starting Document Service")
    
    # Подключение к Redis
    await redis_client.connect()
    logger.info("Connected to Redis")

@app.on_event("shutdown")
async def shutdown_event():
    """Событие остановки приложения"""
    logger.info("Shutting down Document Service")
    
    # Отключение от Redis
    await redis_client.disconnect()
    logger.info("Disconnected from Redis")

@app.get("/health")
async def health_check():
    """Проверка здоровья сервиса"""
    return {
        "status": "healthy",
        "service": "document-service",
        "version": "1.0.0"
    }

@app.get("/")
async def root():
    """Корневой эндпоинт"""
    return {
        "message": "ERP Document Service",
        "docs": "/docs",
        "health": "/health"
    }

if __name__ == "__main__":
    uvicorn.run(
        "app.main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level=settings.LOG_LEVEL.lower()
    )
