from fastapi import HTTPException
import logging
from typing import List
import base64
import os
from core.celery_app import celery_app
from core.database import CoreSessionLocal
from .service import PedimentosWinsaaiService

logger = logging.getLogger(__name__)

@celery_app.task(bind=True)
def generate_pedimentos_winsaai_task(self, pedimento_ids: List[int], is_temporal: bool, is_by_class: bool = False):
    logger.info(f"Starting Pedimentos WINSAAI task {self.request.id} for pedimentos {pedimento_ids} (by_class={is_by_class})")
    db = CoreSessionLocal()
    try:
        self.update_state(state='PROCESSING', meta={'current': 10, 'status': 'Cargando servicio...'})
        service = PedimentosWinsaaiService(db)
        
        self.update_state(state='PROCESSING', meta={'current': 30, 'status': 'Generando datos...'})
        lines = service.generate_pedimentos_data(pedimento_ids, is_temporal, is_by_class)
        
        self.update_state(state='PROCESSING', meta={'current': 70, 'status': 'Guardando archivo...'})
        # Use first pedimento number for filename
        from api.v1.modules.a76.pedmientos.models.pedimentos import Pedimentos
        ped = db.query(Pedimentos).filter(Pedimentos.id == pedimento_ids[0]).first() if pedimento_ids else None
        if ped:
            filename = f"{ped.year}-{ped.license}-{ped.pedimento_number}.txt"
        else:
            filename = "pedimentos.txt"
        filepath = f"/tmp/{filename}"
        
        # Clarion uses ANSI/UTF-8 usually, but let's stick to UTF-8 for now unless specific requirement
        with open(filepath, "w", encoding="utf-8") as f:
            f.write("\n".join(lines))
        
        self.update_state(state='PROCESSING', meta={'current': 90, 'status': 'Finalizando...'})
        with open(filepath, "rb") as f:
            content_b64 = base64.b64encode(f.read()).decode("utf-8")
        
        return {
            "status": "success",
            "content": content_b64,
            "filepath": filepath,
            "filename": filename,
            "file_name": filename,
            "media_type": "text/plain",
            "validation_errors": [e.model_dump() for e in service.validation_errors]
        }
    except Exception as e:
        logger.error(f"Error in generate_pedimentos_winsaai_task: {str(e)}", exc_info=True)
        raise e
    finally:
        db.close()
