from fastapi import HTTPException
from core.celery_app import celery_app
from core.database import CoreSessionLocal
from .service import WinsaaiService
import os
import tempfile

import logging
import sys

logger = logging.getLogger(__name__)

@celery_app.task(bind=True)
def generate_winsaai_task(self, invoice_ids: list, is_temporal: bool):
    logger.info(f"Starting WINSAAI task {self.request.id} for {invoice_ids}")
    db = CoreSessionLocal()
    try:
        self.update_state(state='PROCESSING', meta={'current': 10, 'status': 'Cargando servicio...'})
        from api.v1.modules.a76.invoices.models import InvoiceHeader as _InvH
        _first = db.query(_InvH).filter(_InvH.id == invoice_ids[0]).first() if invoice_ids else None
        _company_id = _first.company_id if _first else 0
        _tenant_id = _first.tenant_id if _first else 0
        service = WinsaaiService(db, _company_id, _tenant_id)
        
        self.update_state(state='PROCESSING', meta={'current': 30, 'status': 'Generando datos...'})
        lines = service.generate_winsaai_data(invoice_ids, is_temporal)
        
        self.update_state(state='PROCESSING', meta={'current': 70, 'status': 'Guardando archivo...'})
        
        # Determine filename
        from api.v1.modules.a76.invoices.models import InvoiceHeader
        first_invoice = db.query(InvoiceHeader).filter(InvoiceHeader.id == invoice_ids[0]).first() if invoice_ids else None
        filename = f"{first_invoice.invoice_number}.txt" if first_invoice else f"winsaai_{self.request.id}.txt"
            
        temp_dir = tempfile.gettempdir()
        filepath = os.path.join(temp_dir, filename)
        
        with open(filepath, "w", encoding="latin-1") as f:
            for line in lines:
                f.write(line + "\n")
        
        self.update_state(state='PROCESSING', meta={'current': 90, 'status': 'Finalizando...'})
        
        import base64
        with open(filepath, "rb") as f:
            encoded_content = base64.b64encode(f.read()).decode('utf-8')
        
        logger.info(f"WINSAAI task {self.request.id} completed successfully")
        return {
            "status": "success",
            "content": encoded_content,
            "filepath": filepath,
            "filename": filename,
            "file_name": filename,
            "media_type": "text/plain",
            "validation_errors": []
        }
    except Exception as e:
        logger.error(f"Error in generate_winsaai_task: {str(e)}", exc_info=True)
        # No actualizar estado a FAILURE manualmente, dejar que Celery lo haga al re-lanzar
        raise e
    finally:
        db.close()
