from fastapi import APIRouter, HTTPException, Depends
from app.services.set_label_service import SetLabelService
from app.services.label_printer_service import LabelPrinterService
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]

router = APIRouter(prefix="/set-labels")
set_label_service = SetLabelService()
label_printer_service = LabelPrinterService(printer_api_url="http://192.168.1.110:8000")

@router.post("/generate")
async def generate_set_labels(request: SetLabelRequest):
    """
    Generate PDF labels for the specified MTG sets.
    
    Args:
        request: Request body containing list of set codes to generate labels for
    
    Returns:
        Message indicating success or failure
    """
    try:
        set_pdfs = await set_label_service.generate_labels(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:
        sets = await set_label_service.get_available_sets(db)
        return sets
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))