"""
Celery worker для отправки запланированных уведомлений
"""
from celery import shared_task
from sqlalchemy.orm import Session
from datetime import datetime

from app.db.session import SessionLocal
from app.db.models import (
    ScheduledNotification, Notification, Customer,
    Template, UserIndustryTemplate, IndustryTemplate
)
from app.workers.notifications import enqueue_notification
from app.core.config import get_settings


@shared_task(bind=True, name="app.workers.scheduled_sender.send_scheduled_notifications")
def send_scheduled_notifications(self):
    """
    Отправка запланированных уведомлений.
    Запускается каждую минуту через Celery Beat.
    """
    db: Session = SessionLocal()
    
    try:
        now = datetime.utcnow()
        
        # Находим уведомления, которые нужно отправить
        # Ограничиваем количество для обработки за один запуск (батчинг)
        # Это предотвращает перегрузку при большом количестве запланированных уведомлений
        settings = get_settings()
        batch_size = settings.SCHEDULED_NOTIFICATIONS_BATCH_SIZE
        
        scheduled_list = db.query(ScheduledNotification).filter(
            ScheduledNotification.scheduled_at <= now,
            ScheduledNotification.status == 'pending'
        ).order_by(ScheduledNotification.scheduled_at.asc()).limit(batch_size).all()
        
        sent_count = 0
        
        for scheduled in scheduled_list:
            try:
                # Получаем клиента
                customer = db.query(Customer).filter(
                    Customer.id == scheduled.customer_id
                ).first()
                
                if not customer:
                    scheduled.status = 'failed'
                    continue
                
                # Получаем шаблон
                template = None
                content = None
                
                if scheduled.template_id:
                    template = db.query(Template).filter(
                        Template.id == scheduled.template_id
                    ).first()
                    content = template.content if template else None
                
                # Если используется industry template, берём контент оттуда
                if scheduled.user_template_id:
                    user_template = db.query(UserIndustryTemplate).filter(
                        UserIndustryTemplate.id == scheduled.user_template_id
                    ).first()
                    
                    if user_template and user_template.custom_content:
                        content = user_template.custom_content
                    elif user_template:
                        industry_template = db.query(IndustryTemplate).filter(
                            IndustryTemplate.id == user_template.industry_template_id
                        ).first()
                        
                        if industry_template:
                            content = industry_template.content
                
                if not content:
                    scheduled.status = 'failed'
                    continue
                
                # Создаём уведомление
                notification = Notification(
                    tenant_id=scheduled.tenant_id,
                    template_id=scheduled.template_id,
                    customer_id=scheduled.customer_id,
                    payload=scheduled.payload or {},
                    status='pending'
                )
                db.add(notification)
                db.flush()
                
                # Отправляем через существующий механизм
                enqueue_notification.delay(notification.id)
                
                # Обновляем статус scheduled
                scheduled.status = 'sent'
                scheduled.sent_at = datetime.utcnow()
                scheduled.notification_id = notification.id
                
                sent_count += 1
                
            except Exception as e:
                print(f"Error sending scheduled notification {scheduled.id}: {e}")
                scheduled.status = 'failed'
                continue
        
        db.commit()
        
        return {
            'status': 'success',
            'sent_count': sent_count,
            'checked_at': now.isoformat()
        }
        
    except Exception as e:
        print(f"Error in send_scheduled_notifications: {e}")
        return {
            'status': 'error',
            'error': str(e)
        }
    finally:
        db.close()


@shared_task(bind=True, name="app.workers.scheduled_sender.cleanup_old_scheduled")
def cleanup_old_scheduled(self):
    """
    Очистка старых отправленных уведомлений
    Запускается раз в день
    """
    db: Session = SessionLocal()
    
    try:
        from datetime import timedelta
        
        # Удаляем отправленные старше 30 дней
        cutoff_date = datetime.utcnow() - timedelta(days=30)
        
        deleted = db.query(ScheduledNotification).filter(
            ScheduledNotification.status == 'sent',
            ScheduledNotification.sent_at < cutoff_date
        ).delete()
        
        db.commit()
        
        return {
            'status': 'success',
            'deleted_count': deleted
        }
    
    finally:
        db.close()



















