"""
Celery Tasks - Background Task Processing
"""
import logging
import time
from typing import Any, Dict
from celery import current_task
from celery.utils.log import get_task_logger
from src.worker.celery_app import celery_app

# Use Celery's task logger for proper distributed logging
logger = get_task_logger(__name__)


@celery_app.task(bind=True, name="send_welcome_email")
def send_welcome_email(self, user_email: str, user_name: str) -> Dict[str, Any]:
    """
    Send welcome email task - Simple example for demonstration
    
    Args:
        user_email: User's email address
        user_name: User's display name
        
    Returns:
        Dict containing task result information
    """
    try:
        logger.info(f"Sending welcome email to {user_email} for user {user_name}")
        
        # Simulate email sending work (replace with real email service)
        time.sleep(2)  # Simulate API call delay
        
        # In a real implementation, you would integrate with:
        # - SMTP server
        # - SendGrid, SES, Mailgun, etc.
        # - Email template engine
        
        result = {
            "task_id": self.request.id,
            "email": user_email,
            "name": user_name,
            "status": "sent",
            "timestamp": time.time()
        }
        
        logger.info(f"Welcome email sent successfully to {user_email}")
        return result
        
    except Exception as exc:
        logger.error(f"Welcome email sending failed: {str(exc)}")
        # Retry the task after 60 seconds, max 3 times
        raise self.retry(exc=exc, countdown=60, max_retries=3)


@celery_app.task(name="health_check")
def health_check() -> Dict[str, Any]:
    """
    Health check task for monitoring worker status
    
    Returns:
        Dict containing health check result
    """
    logger.info("Performing health check")
    
    return {
        "status": "healthy",
        "timestamp": time.time(),
        "worker_id": current_task.request.hostname if current_task else "unknown"
    }


# Utility function to get task status
def get_task_status(task_id: str) -> Dict[str, Any]:
    """
    Get status of a task by ID
    
    Args:
        task_id: Celery task ID
        
    Returns:
        Dict containing task status information
    """
    if not celery_app:
        return {"error": "Celery not available"}
        
    try:
        result = celery_app.AsyncResult(task_id)
        
        return {
            "task_id": task_id,
            "status": result.status,
            "result": result.result,
            "traceback": result.traceback,
            "date_done": result.date_done,
        }
    except Exception as exc:
        logger.error(f"Error getting task status: {str(exc)}")
        return {
            "task_id": task_id,
            "status": "UNKNOWN",
            "error": str(exc)
        }


# Convenience function for FastAPI integration
def trigger_welcome_email(user_email: str, user_name: str) -> str:
    """
    Trigger welcome email task from FastAPI
    
    Returns:
        str: Task ID
    """
    if not celery_app:
        raise RuntimeError("Celery not available")
        
    task = send_welcome_email.delay(user_email, user_name)
    return task.id


# Export functions for FastAPI imports
__all__ = [
    "send_welcome_email",
    "health_check", 
    "get_task_status",
    "trigger_welcome_email"
]