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.scheduler.scheduler_service import SchedulerService
from app.services.data_initialization import DataInitializationService
from datetime import datetime
# 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 scheduler service
scheduler_service = SchedulerService()
data_init_service = DataInitializationService()

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    init_db()
    logger.info("Database initialized successfully")
    
    # Initialize TCGPlayer data
    db = SessionLocal()
    try:
        await data_init_service.initialize_data(db, game_ids=[1, 3], init_archived_prices=False, archived_prices_start_date="2025-04-01", archived_prices_end_date=datetime.now().strftime("%Y-%m-%d"), init_categories=False, init_groups=False, init_products=False) # 1 = Magic, 3 = Pokemon
        logger.info("TCGPlayer data initialized successfully")
    except Exception as e:
        logger.error(f"Failed to initialize TCGPlayer data: {str(e)}")
    finally:
        db.close()
    
    # Start the scheduler
    await scheduler_service.start_scheduled_tasks()
    await scheduler_service.process_tcgplayer_export(export_type="live", use_cache=True)
    logger.info("Scheduler started successfully")
    
    yield
    
    # Shutdown
    await scheduler_service.scheduler.shutdown()
    await data_init_service.close()
    logger.info("Scheduler shut down")
    logger.info("Database connection closed")

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)
