"""
مهام التقارير - Celery Tasks
"""
import asyncio
from datetime import datetime, timedelta
from app.celery_app import celery_app


@celery_app.task
def send_daily_report():
    """إرسال تقرير يومي"""
    try:
        from app.database import async_session_maker
        from app.models.tenant import Tenant
        from app.models.device import Device
        from app.models.alert import AlertLog
        from app.models.settings import TenantSettings
        from app.services.notifications import notification_service
        from app.services.reports import report_service
        from sqlalchemy import select, func
        
        async def _send_reports():
            async with async_session_maker() as session:
                # جلب المستأجرين النشطين
                result = await session.execute(
                    select(Tenant).where(Tenant.is_active == True)
                )
                tenants = result.scalars().all()
                
                sent_count = 0
                for tenant in tenants:
                    # جلب إعدادات المستأجر
                    settings_result = await session.execute(
                        select(TenantSettings).where(TenantSettings.tenant_id == tenant.id)
                    )
                    settings = settings_result.scalar_one_or_none()
                    
                    if not settings or not settings.alert_email_enabled:
                        continue
                    
                    recipients = settings.alert_recipients or []
                    if not recipients:
                        continue
                    
                    # جلب إحصائيات اليوم
                    yesterday = datetime.utcnow() - timedelta(days=1)
                    
                    # عدد الأجهزة
                    devices_count = await session.scalar(
                        select(func.count(Device.id)).where(Device.tenant_id == tenant.id)
                    )
                    online_count = await session.scalar(
                        select(func.count(Device.id)).where(
                            Device.tenant_id == tenant.id,
                            Device.is_online == True
                        )
                    )
                    
                    # عدد التنبيهات
                    alerts_count = await session.scalar(
                        select(func.count(AlertLog.id)).where(
                            AlertLog.tenant_id == tenant.id,
                            AlertLog.triggered_at >= yesterday
                        )
                    )
                    
                    # بناء التقرير
                    html_report = f"""
                    <html dir="rtl">
                    <body style="font-family: Arial; padding: 20px;">
                        <h1>التقرير اليومي - {tenant.name}</h1>
                        <p>التاريخ: {datetime.now().strftime('%Y-%m-%d')}</p>
                        <hr>
                        <h2>إحصائيات الأجهزة</h2>
                        <ul>
                            <li>إجمالي الأجهزة: {devices_count}</li>
                            <li>الأجهزة المتصلة: {online_count}</li>
                            <li>الأجهزة غير المتصلة: {devices_count - online_count}</li>
                        </ul>
                        <h2>التنبيهات (آخر 24 ساعة)</h2>
                        <ul>
                            <li>عدد التنبيهات: {alerts_count}</li>
                        </ul>
                        <hr>
                        <p>SmartLife IoT Platform</p>
                    </body>
                    </html>
                    """
                    
                    # إرسال البريد
                    smtp_config = {
                        'host': settings.smtp_host,
                        'port': settings.smtp_port,
                        'username': settings.smtp_username,
                        'password': settings.smtp_password,
                        'from_email': settings.smtp_from_email,
                        'from_name': settings.smtp_from_name,
                        'use_tls': settings.smtp_use_tls,
                        'use_ssl': settings.smtp_use_ssl,
                    }
                    
                    if smtp_config.get('host'):
                        await notification_service.send_email(
                            smtp_config,
                            recipients,
                            f"التقرير اليومي - {tenant.name}",
                            html_report
                        )
                        sent_count += 1
                
                return sent_count
        
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        result = loop.run_until_complete(_send_reports())
        loop.close()
        
        return {"status": "success", "sent_reports": result, "timestamp": datetime.now().isoformat()}
        
    except Exception as e:
        return {"status": "error", "error": str(e)}


@celery_app.task
def generate_monthly_report(tenant_id: str):
    """إنشاء تقرير شهري"""
    try:
        return {"status": "success", "tenant_id": tenant_id}
    except Exception as e:
        return {"status": "error", "error": str(e)}
