from celery import Task
from fastapi import HTTPException
from core.celery_app import celery_app
from core.celery_app import celery_app
from core.database import get_core_db as get_db
from .service import Mainx30Service
from .schemas import Mainx30GenerationRequest, Mainx30Response

@celery_app.task(name="generar_transmission_file_async", bind=True)
def generar_transmission_file_async(self, request_data: dict, tenant_id: int):
    """
    Generates the transmission .dat file asynchronously using Mainx30Service
    """
    try:
        # Re-create db session for task
        # Using next(get_db()) is a common pattern for obtaining a session in tasks
        # but ensure context management
        db = next(get_db())
        
        # Deserialize request
        request = Mainx30GenerationRequest(**request_data)
        
        service = Mainx30Service()
        response = service.generar_mainx30_expo(db, request, task_instance=self)
        
        # Return result as dict for Celery serialization
        # Ensure we return valid JSON serializable dict
        result = response.model_dump()
        
        # If we returned content directly, encode it if it's bytes (it's str here)
        if response.content:
            import base64
            # Mainx30Service returns content as string with \r\n
            encoded_content = base64.b64encode(response.content.encode('utf-8')).decode('utf-8')
            # Add to result to match expected format by frontend dialog
            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_exc()
        self.update_state(state='FAILURE', meta={'exc_type': type(e).__name__, 'exc_message': str(e)})
        # Re-raise to mark task as failed in Celery
        raise e
