from fastapi import HTTPException
from core.celery_app import celery_app
from core.database import get_core_db as get_db
from .service import Mainx30DefinitiveService
from .schemas import Mainx30GenerationRequest

@celery_app.task(name="generar_transmission_definitiva_async", bind=True)
def generar_transmission_definitiva_async(self, request_data: dict, tenant_id: int):
    """
    Celery task to generate Mainx30 file for Definitive Import
    """
    try:
        # Re-create db session for task
        db = next(get_db())
        
        # Deserialize request
        request = Mainx30GenerationRequest(**request_data)
        
        service = Mainx30DefinitiveService()
        response = service.generar_mainx30(db, request, task_instance=self)
        
        # Return result as dict for Celery serialization
        result = response.model_dump()
        
        # Add base64 encoding for content to match frontend expectations
        if response.content:
            import base64
            encoded_content = base64.b64encode(response.content.encode('utf-8')).decode('utf-8')
            result['content'] = encoded_content
            result['file_name'] = response.archivo_generado
            result['media_type'] = "text/plain"

        return result
        
    except Exception as e:
        import traceback
        traceback_print = traceback.format_exc()
        self.update_state(
            state='FAILURE',
            meta={
                'exc_type': type(e).__name__,
                'exc_message': str(e),
                'traceback': traceback_print
            }
        )
        raise e
