"""
Background Scheduler لفحص التنبيهات تلقائياً
"""
import threading
import time
from datetime import datetime

_scheduler_running = False
_scheduler_thread = None


def alert_check_job():
    """فحص التنبيهات باستخدام sync database"""
    from sqlalchemy import create_engine, select, and_
    from sqlalchemy.orm import Session
    from datetime import timedelta
    import pytz
    import os
    
    RIYADH_TZ = pytz.timezone('Asia/Riyadh')
    
    def get_local_time():
        return datetime.now(RIYADH_TZ)
    
    try:
        # إنشاء sync engine
        from app.config import settings
        db_url = settings.DATABASE_URL
        sync_url = db_url.replace("+aiomysql", "+pymysql")
        engine = create_engine(sync_url)
        
        from app.models.device import Device
        from app.models.alert import AlertRule, AlertLog
        from app.models.settings import TenantSettings
        from app.services.email_service import EmailService
        
        with Session(engine) as session:
            # جلب قواعد التنبيهات النشطة
            rules = session.execute(
                select(AlertRule).where(AlertRule.is_active == True)
            ).scalars().all()
            
            if not rules:
                print(f"[Scheduler] No active rules")
                return
            
            triggered_count = 0
            emails_sent = 0
            
            for rule in rules:
                device = session.get(Device, rule.device_id)
                if not device or not device.device_metadata:
                    continue
                
                readings = device.device_metadata.get('readings', {})
                current_value = readings.get(rule.reading_type)
                if current_value is None:
                    continue
                
                # التحقق من الشرط
                threshold = float(rule.threshold_value) if rule.threshold_value else 0
                condition_met = False
                
                if rule.condition_type == 'greater_than' and current_value > threshold:
                    condition_met = True
                elif rule.condition_type == 'less_than' and current_value < threshold:
                    condition_met = True
                elif rule.condition_type == 'equals' and current_value == threshold:
                    condition_met = True
                
                if not condition_met:
                    continue
                
                # جلب إعدادات المستأجر
                settings_obj = session.execute(
                    select(TenantSettings).where(TenantSettings.tenant_id == rule.tenant_id)
                ).scalar_one_or_none()
                
                if not settings_obj:
                    continue
                
                # جلب آخر تنبيه
                last_alert = session.execute(
                    select(AlertLog).where(
                        and_(AlertLog.alert_rule_id == rule.id, AlertLog.is_resolved == False)
                    ).order_by(AlertLog.triggered_at.desc()).limit(1)
                ).scalar_one_or_none()
                
                now = get_local_time().replace(tzinfo=None)
                cooldown_minutes = settings_obj.alert_cooldown_minutes or 1
                
                # تحقق من cooldown
                if last_alert:
                    time_since_last = now - last_alert.triggered_at
                    if time_since_last < timedelta(minutes=cooldown_minutes):
                        print(f"[Scheduler] {rule.name}: In cooldown ({time_since_last.total_seconds()/60:.1f} min < {cooldown_minutes} min)")
                        continue
                
                # إنشاء تنبيه جديد
                is_reminder = last_alert is not None
                alert_log = AlertLog(
                    tenant_id=rule.tenant_id,
                    alert_rule_id=rule.id,
                    device_id=device.id,
                    title=f"{'[تذكير] ' if is_reminder else ''}{rule.name}",
                    message=f"{rule.reading_type}: {current_value}",
                    severity=rule.severity,
                    reading_value=float(current_value),
                    triggered_at=now
                )
                session.add(alert_log)
                rule.last_triggered = now
                triggered_count += 1
                
                # إرسال إيميل
                if settings_obj.alert_email_enabled and settings_obj.alert_email_recipients:
                    try:
                        email_service = EmailService(settings_obj)
                        recipients = [e.strip() for e in settings_obj.alert_email_recipients.split(',') if e.strip()]
                        sent = email_service.send_alert_email(
                            to_emails=recipients,
                            alert_type="reminder" if is_reminder else "threshold",
                            device_name=device.name,
                            device_id=str(device.id),
                            reading_type=rule.reading_type,
                            current_value=current_value,
                            threshold_value=threshold,
                            condition=rule.condition_type,
                            severity=rule.severity,
                            location=device.location,
                            dashboard_url="https://smart-life.online"
                        )
                        emails_sent += sent
                        print(f"[Scheduler] ✓ Email sent to {recipients}")
                    except Exception as e:
                        print(f"[Scheduler] Email error: {e}")
            
            session.commit()
            print(f"[Scheduler] Alert check: triggered={triggered_count}, emails={emails_sent}")
        
        engine.dispose()
        
    except Exception as e:
        print(f"[Scheduler] Error: {e}")


def scheduler_loop(interval_seconds: int = 60):
    """حلقة الـ Scheduler"""
    global _scheduler_running
    
    print(f"[Scheduler] Started - checking alerts every {interval_seconds} seconds")
    
    while _scheduler_running:
        try:
            alert_check_job()
        except Exception as e:
            print(f"[Scheduler] Job error: {e}")
        
        # الانتظار مع التحقق من إيقاف الـ scheduler
        for _ in range(interval_seconds):
            if not _scheduler_running:
                break
            time.sleep(1)
    
    print("[Scheduler] Stopped")


def start_scheduler(interval_seconds: int = 60):
    """بدء الـ Scheduler"""
    global _scheduler_running, _scheduler_thread
    
    if _scheduler_running:
        print("[Scheduler] Already running")
        return
    
    _scheduler_running = True
    _scheduler_thread = threading.Thread(
        target=scheduler_loop, 
        args=(interval_seconds,),
        daemon=True
    )
    _scheduler_thread.start()
    print(f"[Scheduler] Started in background thread")


def stop_scheduler():
    """إيقاف الـ Scheduler"""
    global _scheduler_running, _scheduler_thread
    
    _scheduler_running = False
    if _scheduler_thread:
        _scheduler_thread.join(timeout=5)
        _scheduler_thread = None
    print("[Scheduler] Stopped")


def is_scheduler_running():
    """التحقق من حالة الـ Scheduler"""
    return _scheduler_running
