"""
Celery task for asynchronous Saldos Temporales CSV generation.
"""
import base64
import logging
from typing import Dict, Any

from core.celery_app import celery_app
from core.email import EmailService
from datetime import datetime

from .schemas import SaldosFilter
from .csv_utils import generate_saldos_csv

logger = logging.getLogger(__name__)


@celery_app.task(bind=True, name="generate_saldos_temporales_async")
def generate_saldos_temporales_async(
    self,
    filter_data: Dict[str, Any],
    user_email: str = None
):
    """
    Async Celery task: generate Saldos Temporales CSV and optionally e-mail it.
    """
    try:
        # 1. Progress – initialising
        self.update_state(
            state="PROCESSING",
            meta={"current": 10, "total": 100, "status": "Inicializando reporte de Saldos Temporales..."},
        )

        # 2. Re-construct filter
        filters = SaldosFilter(**filter_data)

        # 3. Fetch + generate CSV  (real DB session)
        self.update_state(
            state="PROCESSING",
            meta={"current": 40, "total": 100, "status": "Generando datos de Saldos Temporales..."},
        )
        logger.info(f"Saldos task: building CSV (range_type={filters.range_type})")

        from core.database import CoreSessionLocal
        db = CoreSessionLocal()
        try:
            csv_content = generate_saldos_csv(filters, db=db)
        finally:
            db.close()

        # 4. Optional e-mail
        email_sent = False
        if filters.send_email and user_email:
            self.update_state(
                state="PROCESSING",
                meta={"current": 85, "total": 100, "status": "Enviando correo electrónico..."},
            )
            try:
                import asyncio
                from asgiref.sync import async_to_sync

                filename = (
                    f"saldos_temporales_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
                )
                result = async_to_sync(EmailService.send_report_email)(
                    recipient_email=user_email,
                    subject=f"Saldos Temporales – {datetime.now().strftime('%d/%m/%Y')}",
                    body_text="Se adjunta el reporte de Saldos Temporales generado.",
                    csv_content=csv_content,
                    filename=filename,
                )
                email_sent = bool(result)
            except Exception as e:
                logger.error(f"Saldos task: email error: {e}")

        # 5. Encode to base64 and return
        self.update_state(
            state="PROCESSING",
            meta={"current": 95, "total": 100, "status": "Finalizando..."},
        )

        content_b64 = base64.b64encode(csv_content.encode("utf-8")).decode("utf-8")
        filename = f"saldos_temporales_{datetime.now().strftime('%Y%m%d')}.csv"

        return {
            "status": "success",
            "file_name": filename,
            "content": content_b64,
            "media_type": "text/csv",
            "email_sent": email_sent,
        }

    except Exception as e:
        logger.error(f"Error in generate_saldos_temporales_async: {e}", exc_info=True)
        self.update_state(
            state="FAILURE",
            meta={
                "exc_type": type(e).__name__,
                "exc_message": str(e),
                "custom": "Error generating Saldos Temporales report",
            },
        )
        raise
