"""
Sync real devices from LifeSmart API - Europe Region
"""
import asyncio
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select
from datetime import datetime
import uuid

# Credentials
LIFESMART_EMAIL = "ithelpdesk@ic.gov.sa"
LIFESMART_PASSWORD = "Dt@1234567"
LIFESMART_APP_KEY = "FzpsFOpzbGfGfeSSbdYefg"
LIFESMART_APP_TOKEN = "jmsPdehjIzhkvKht7ggEaA"
LIFESMART_USER_ID = "8467906"
LIFESMART_USER_TOKEN = "j2tqEbZbZAGMlC9wYu7uzA"
LIFESMART_REGION = "sa"
LIFESMART_API_URL = "https://api.us.ilifesmart.com/app"

DATABASE_URL = "mysql+aiomysql://root:@localhost:3306/smartlife_db?charset=utf8mb4"


async def main():
    from app.models.tenant import Tenant
    from app.models.device import Device
    from app.models.alert import AlertRule
    from app.services.lifesmart_client import LifeSmartClient
    
    engine = create_async_engine(DATABASE_URL, echo=False)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session() as session:
        try:
            # Get tenant
            result = await session.execute(
                select(Tenant).where(Tenant.email == LIFESMART_EMAIL)
            )
            tenant = result.scalar_one_or_none()
            
            if not tenant:
                print("❌ Tenant not found!")
                return
            
            print(f"✅ Found tenant: {tenant.name}")
            
            # Update region
            tenant.lifesmart_region = LIFESMART_REGION
            
            # Connect to LifeSmart API
            print(f"\n🔗 Connecting to LifeSmart API (Region: {LIFESMART_REGION})...")
            client = LifeSmartClient(
                app_key=LIFESMART_APP_KEY,
                app_token=LIFESMART_APP_TOKEN,
                region=LIFESMART_REGION
            )
            
            # Authenticate
            print("🔐 Authenticating...")
            auth_result = await client.authenticate(
                username=LIFESMART_EMAIL,
                password=LIFESMART_PASSWORD
            )
            
            if not auth_result.success:
                print(f"❌ Authentication failed: {auth_result.error}")
                await client.close()
                return
            
            print(f"✅ Authenticated! User ID: {auth_result.user_id}")
            
            # Update tenant credentials
            tenant.lifesmart_user_id = auth_result.user_id
            tenant.lifesmart_user_token = auth_result.user_token
            
            # Fetch devices
            print("\n📱 Fetching devices...")
            devices = await client.get_devices()
            print(f"✅ Found {len(devices)} devices")
            
            if len(devices) == 0:
                print("⚠️ No devices found in your LifeSmart account")
                await client.close()
                await session.commit()
                return
            
            # Sync devices
            new_count = 0
            updated_count = 0
            
            for ls_device in devices:
                result = await session.execute(
                    select(Device).where(
                        Device.tenant_id == tenant.id,
                        Device.lifesmart_device_id == ls_device.device_id
                    )
                )
                existing = result.scalar_one_or_none()
                
                if existing:
                    existing.name = ls_device.name
                    existing.device_type = ls_device.device_type
                    existing.is_online = ls_device.is_online
                    existing.device_metadata = {
                        "hub_id": ls_device.hub_id,
                        "model": ls_device.device_model,
                        "data": ls_device.data,
                        "controls": ls_device.controls,
                        "last_sync": datetime.utcnow().isoformat()
                    }
                    updated_count += 1
                    print(f"   🔄 Updated: {ls_device.name} ({ls_device.device_type}) - {'🟢' if ls_device.is_online else '🔴'}")
                else:
                    new_device = Device(
                        id=uuid.uuid4(),
                        tenant_id=tenant.id,
                        name=ls_device.name,
                        name_ar=ls_device.name,
                        device_type=ls_device.device_type,
                        lifesmart_device_id=ls_device.device_id,
                        lifesmart_hub_id=ls_device.hub_id,
                        device_model=ls_device.device_model,
                        is_online=ls_device.is_online,
                        device_metadata={
                            "hub_id": ls_device.hub_id,
                            "model": ls_device.device_model,
                            "data": ls_device.data,
                            "controls": ls_device.controls,
                            "last_sync": datetime.utcnow().isoformat()
                        }
                    )
                    session.add(new_device)
                    new_count += 1
                    print(f"   ➕ Added: {ls_device.name} ({ls_device.device_type}) - {'🟢' if ls_device.is_online else '🔴'}")
            
            await session.flush()
            
            # Create smart alerts for devices
            print("\n🔔 Creating smart alert rules...")
            result = await session.execute(
                select(Device).where(Device.tenant_id == tenant.id)
            )
            all_devices = result.scalars().all()
            
            alerts_created = 0
            for device in all_devices:
                # Check existing alerts
                result = await session.execute(
                    select(AlertRule).where(AlertRule.device_id == device.id)
                )
                if result.scalars().first():
                    continue
                
                # Create alerts based on device type
                if device.device_type == "environment_sensor":
                    # High temp
                    session.add(AlertRule(
                        id=uuid.uuid4(), tenant_id=tenant.id, device_id=device.id,
                        name=f"تنبيه ارتفاع الحرارة - {device.name}",
                        name_ar=f"تنبيه ارتفاع الحرارة - {device.name}",
                        condition_type="greater_than", threshold_value=35.0,
                        reading_type="temperature", severity="warning",
                        notification_channels=["email", "push"], is_active=True
                    ))
                    # High humidity
                    session.add(AlertRule(
                        id=uuid.uuid4(), tenant_id=tenant.id, device_id=device.id,
                        name=f"تنبيه ارتفاع الرطوبة - {device.name}",
                        name_ar=f"تنبيه ارتفاع الرطوبة - {device.name}",
                        condition_type="greater_than", threshold_value=80.0,
                        reading_type="humidity", severity="warning",
                        notification_channels=["email", "push"], is_active=True
                    ))
                    alerts_created += 2
                    
                elif device.device_type == "motion_sensor":
                    session.add(AlertRule(
                        id=uuid.uuid4(), tenant_id=tenant.id, device_id=device.id,
                        name=f"تنبيه حركة - {device.name}",
                        name_ar=f"تنبيه حركة - {device.name}",
                        condition_type="equals", threshold_value=1,
                        reading_type="motion", severity="info",
                        notification_channels=["push"], is_active=True
                    ))
                    alerts_created += 1
                    
                elif device.device_type == "door_sensor":
                    session.add(AlertRule(
                        id=uuid.uuid4(), tenant_id=tenant.id, device_id=device.id,
                        name=f"تنبيه فتح الباب - {device.name}",
                        name_ar=f"تنبيه فتح الباب - {device.name}",
                        condition_type="equals", threshold_value=1,
                        reading_type="open", severity="info",
                        notification_channels=["push"], is_active=True
                    ))
                    alerts_created += 1
                    
                elif device.device_type in ["gas_sensor", "smoke_sensor"]:
                    session.add(AlertRule(
                        id=uuid.uuid4(), tenant_id=tenant.id, device_id=device.id,
                        name=f"🚨 تنبيه طوارئ - {device.name}",
                        name_ar=f"🚨 تنبيه طوارئ - {device.name}",
                        condition_type="greater_than", threshold_value=0,
                        reading_type="gas_level", severity="critical",
                        notification_channels=["email", "push", "sms"], is_active=True
                    ))
                    alerts_created += 1
                    
                elif device.device_type == "water_leak_sensor":
                    session.add(AlertRule(
                        id=uuid.uuid4(), tenant_id=tenant.id, device_id=device.id,
                        name=f"🚨 تنبيه تسرب مياه - {device.name}",
                        name_ar=f"🚨 تنبيه تسرب مياه - {device.name}",
                        condition_type="equals", threshold_value=1,
                        reading_type="water_leak", severity="critical",
                        notification_channels=["email", "push", "sms"], is_active=True
                    ))
                    alerts_created += 1
                    
                elif device.device_type == "door_lock":
                    session.add(AlertRule(
                        id=uuid.uuid4(), tenant_id=tenant.id, device_id=device.id,
                        name=f"تنبيه فتح القفل - {device.name}",
                        name_ar=f"تنبيه فتح القفل - {device.name}",
                        condition_type="equals", threshold_value=0,
                        reading_type="locked", severity="warning",
                        notification_channels=["email", "push"], is_active=True
                    ))
                    alerts_created += 1
                
                # Offline alert for all devices
                session.add(AlertRule(
                    id=uuid.uuid4(), tenant_id=tenant.id, device_id=device.id,
                    name=f"تنبيه انقطاع الاتصال - {device.name}",
                    name_ar=f"تنبيه انقطاع الاتصال - {device.name}",
                    condition_type="equals", threshold_value=0,
                    reading_type="online", severity="warning",
                    notification_channels=["email"], is_active=True
                ))
                alerts_created += 1
            
            await session.commit()
            await client.close()
            
            print(f"\n{'='*50}")
            print(f"📊 Sync Summary:")
            print(f"   ✅ New devices: {new_count}")
            print(f"   🔄 Updated devices: {updated_count}")
            print(f"   🔔 Alert rules created: {alerts_created}")
            print(f"{'='*50}")
            print(f"\n✅ Sync complete!")
            
        except Exception as e:
            print(f"❌ Error: {str(e)}")
            import traceback
            traceback.print_exc()
            await session.rollback()
    
    await engine.dispose()


if __name__ == "__main__":
    asyncio.run(main())
