from fastapi import HTTPException
import base64
from core.celery_app import celery_app
from core.database import CoreSessionLocal
from .service import PackingListService

@celery_app.task(bind=True)
def generar_packing_list_async(self, invoice_id: int, company_id: int):
    """
    Tarea asíncrona para generar el Packing List
    """
    db = CoreSessionLocal()
    try:
        service = PackingListService()

        def update_progress(percent, message):
            self.update_state(
                state='PROCESSING',
                meta={
                    'current': percent,
                    'total': 100,
                    'status': message
                }
            )

        pdf_bytes, filename = service.generate_pdf(db, invoice_id, company_id, update_progress)
        
        # Codificar a base64 para enviar por JSON
        pdf_b64 = base64.b64encode(pdf_bytes).decode('utf-8')
        
        return {
            'status': 'success',
            'file_name': filename,
            'content': pdf_b64,
            'media_type': 'application/pdf'
        }
        
    except Exception as e:
        print(f"Error en tarea Packing List: {e}")
        import traceback
        traceback.print_exc()
        self.update_state(
            state='FAILURE',
            meta={
                'exc_type': type(e).__name__,
                'exc_message': str(e),
                'custom': 'Error generating PDF'
            }
        )
        raise e
    finally:
        db.close()
