from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import uvicorn
import logging
import os
from app.routes import routes
from app.db.database import init_db, SessionLocal
from app.services.service_manager import ServiceManager
import logging

# Configure logging
log_file = "app.log"
if os.path.exists(log_file):
    os.remove(log_file)  # Remove existing log file to start fresh

# Create a formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')

# Create handlers
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)

file_handler = logging.FileHandler(log_file, mode='w', encoding='utf-8')
file_handler.setFormatter(formatter)

# Configure root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
root_logger.addHandler(console_handler)
root_logger.addHandler(file_handler)

# Get logger for this module
logger = logging.getLogger(__name__)
logger.info("Application starting up...")

# Initialize service manager
service_manager = ServiceManager()

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    init_db()
    logger.info("Database initialized successfully")
    
    # Initialize all services
    await service_manager.initialize_services()
    
    # Start the scheduler
    scheduler = service_manager.get_service('scheduler')
    await scheduler.start_scheduled_tasks()
    logger.info("Scheduler started successfully")
    
    yield
    
    # Shutdown
    await service_manager.cleanup_services()
    logger.info("All services cleaned up successfully")

app = FastAPI(
    title="CCR Cards Management API",
    description="API for managing CCR Cards Inventory, Orders, and more.",
    version="0.1.0",
    lifespan=lifespan
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(routes.router)

if __name__ == "__main__":
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
