import base64
import logging
from core.celery_app import celery_app
from celery import current_task, states
from core.database import CoreSessionLocal 

from .mex.service import FacturaImportacionMexService
from .usa.service import FacturaImportacionUsaService

logger = logging.getLogger(__name__)

@celery_app.task(name="generar_pdf_factura_async", bind=True)
def generar_pdf_factura_async(self, invoice_id: int, company_id: int, invoice_type: str = 'mexican', currency_code: str = 'ORIGINAL'):
   
    db = CoreSessionLocal()
    try:
        logger.info(f"Worker procesando factura {invoice_id} ({invoice_type}, {currency_code})...")
        
        if invoice_type == 'american':
            service = FacturaImportacionUsaService()
        else:
            service = FacturaImportacionMexService()

        self.update_state(state='PROCESSING', meta={'current': 5, 'total': 100, 'status': 'Iniciando generación...'})
        
        def progress_callback(progress: int, status: str):
            self.update_state(state='PROCESSING', meta={'current': progress, 'total': 100, 'status': status})

        pdf_bytes, nombre, media_type = service.generar_factura_completa(
            db=db, 
            invoice_id=invoice_id, 
            company_id=company_id,
            progress_callback=progress_callback,
            currency_code=currency_code
        )
        
    
        pdf_base64 = base64.b64encode(pdf_bytes).decode('utf-8')
        
        return {
            "status": "success",
            "file_name": nombre,
            "content": pdf_base64,
            "media_type": media_type
        }

    except Exception as e:
        logger.error(f"Error en Celery Worker: {str(e)}")
        return {"status": "error", "message": str(e)}
    
    finally:
        
        db.close()