
from celery import shared_task
from sqlalchemy.orm import Session
from core.database import CoreSessionLocal as SessionLocal
from .service import DescargaReportService # FORCE RELOAD 2
from fastapi import HTTPException
import base64
import traceback

@shared_task(bind=True, name="generate_descarga_pdf_task")
def generate_descarga_pdf_task(self, invoice_id: int, company_id: int):
    """
    Tarea de Celery para generar el PDF del Reporte de Descarga
    """
    db: Session = SessionLocal()
    try:
        service = DescargaReportService()

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

        pdf_bytes, filename, content_type = service.generar_pdf(
            db=db,
            invoice_id=invoice_id,
            company_id=company_id,
            progress_callback=update_progress
        )

        # Retornar el PDF en base64 para que el front lo descargue
        pdf_b64 = base64.b64encode(pdf_bytes).decode('utf-8')
        
        return {
            "status": "success",
            "file_name": filename,
            "content": pdf_b64,
            "media_type": content_type,
            "message": "Reporte generado correctamente"
        }

    except Exception as e:
        self.update_state(
            state='FAILURE',
            meta={'exc_type': type(e).__name__, 'exc_message': str(e)}
        )
        raise e
    finally:
        db.close()
