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
from app.services.external_api.tcgplayer.order_management_service import OrderManagementService
from app.services.address_label_service import AddressLabelService
from app.services.pull_sheet_service import PullSheetService
from app.services.print_service import PrintService
from app.services.label_printer_service import LabelPrinterService
from app.services.regular_printer_service import RegularPrinterService
# 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()
order_management_service = OrderManagementService()
address_label_service = AddressLabelService()
pull_sheet_service = PullSheetService()
#print_service = PrintService(printer_name="MFCL2750DW-3", printer_api_url="http://192.168.1.110:8000/print")
label_printer_service = LabelPrinterService(printer_api_url="http://192.168.1.110:8000")
regular_printer_service = RegularPrinterService(printer_name="MFCL2750DW-3")
@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-01-01", archived_prices_end_date=datetime.now().strftime("%Y-%m-%d"), init_categories=True, init_groups=True, init_products=True) # 1 = Magic, 3 = Pokemon
        orders = await order_management_service.get_orders()
        ready_orders = [order for order in orders if order.get("orderStatus") == "Ready to Ship"]
        #logger.info(ready_orders)

        order_ids = [order.get("orderNumber") for order in ready_orders]
        # get only the first 3 order ids
        order_ids = order_ids[:3]
        #logger.info(order_ids)
        packing_slip = await order_management_service.get_packing_slip(order_ids)
        packing_slip_file = await order_management_service.save_file(packing_slip, f"packing_slip_{datetime.now().strftime('%Y-%m-%d')}.pdf")
        await label_printer_service.print_file(packing_slip_file, label_size="dk1241", label_type="packing_slip")

        #pull_sheet = await order_management_service.get_pull_sheet(order_ids)
        #pull_sheet_file = await order_management_service.save_file(pull_sheet, f"pull_sheet_{datetime.now().strftime('%Y-%m-%d')}.csv")
        #await regular_printer_service.print_file(pull_sheet_file)

        shipping_csv = await order_management_service.get_shipping_csv(order_ids)
        shipping_csv_file = await order_management_service.save_file(shipping_csv, f"shipping_csv_{datetime.now().strftime('%Y-%m-%d')}.csv")
        
        # Wait for the file to be saved before generating labels
        if not shipping_csv_file:
            logger.error("Failed to save shipping CSV file")
            return
            
        shipping_labels_dk1241 = address_label_service.generate_labels_from_csv(shipping_csv_file, label_type="dk1241")
        if not shipping_labels_dk1241:
            logger.error("Failed to generate shipping labels")
            return
            
        for label in shipping_labels_dk1241:
            if not label:
                logger.error("Empty label path in shipping labels list")
                continue
            await label_printer_service.print_file(label, label_size="dk1241", label_type="address_label")
            
        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)
