from fastapi import APIRouter, HTTPException, Depends
from app.services.service_manager import ServiceManager
from typing import List, Optional
import asyncio
from app.db.database import get_db
from sqlalchemy.orm import Session
from pydantic import BaseModel

class SetLabelRequest(BaseModel):
    sets: List[str]

# Initialize service manager
service_manager = ServiceManager()

router = APIRouter(prefix="/set-labels")

@router.post("/generate")
async def generate_set_labels(request: SetLabelRequest, db: Session = Depends(get_db)):
    """
    Generate PDF labels for the specified MTG sets.
    
    Args:
        request: Request body containing list of set codes to generate labels for
        db: Database session
    
    Returns:
        Message indicating success or failure
    """
    try:
        set_label_service = service_manager.get_service('set_label')
        label_printer_service = service_manager.get_service('label_printer')
        
        set_pdfs = await set_label_service.generate_labels(db, request.sets)
        for set_pdf in set_pdfs:
            success = await label_printer_service.print_file(set_pdf, label_size="dk1201", label_type="set_label")
            if not success:
                raise HTTPException(status_code=500, detail=f"Failed to print")
        return {
            "message": "Labels printed successfully"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/available-sets")
async def get_available_sets(db: Session = Depends(get_db)):
    """
    Get a list of available MTG sets that can be used for label generation.
    
    Returns:
        List of set codes and their names
    """
    try:
        set_label_service = service_manager.get_service('set_label')
        sets = await set_label_service.get_available_sets(db)
        return sets
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))