"""
Script to setup IC tenant with LifeSmart integration
"""
import asyncio
import sys
import os

# Add parent directory to path
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, text
from datetime import datetime
import uuid

# LifeSmart Credentials
LIFESMART_EMAIL = "ithelpdesk@ic.gov.sa"
LIFESMART_PASSWORD = "ithelpdesk"
LIFESMART_APP_KEY = "FzpsFOpzbGfGfeSSbdYefg"
LIFESMART_APP_TOKEN = "jmsPdehjIzhkvKht7ggEaA"
LIFESMART_REGION = "global"  # Try global region first

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


async def main():
    from app.models.tenant import Tenant
    from app.models.user import User
    from app.models.device import Device
    from app.models.alert import AlertRule
    from app.services.lifesmart_client import LifeSmartClient
    from app.database import Base
    import hashlib
    
    # Create engine and session
    engine = create_async_engine(DATABASE_URL, echo=True)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session() as session:
        try:
            # Check if tenant already exists
            result = await session.execute(
                select(Tenant).where(Tenant.email == LIFESMART_EMAIL)
            )
            existing_tenant = result.scalar_one_or_none()
            
            if existing_tenant:
                print(f"✅ Tenant already exists: {existing_tenant.name}")
                tenant = existing_tenant
            else:
                # Create new tenant
                tenant = Tenant(
                    id=uuid.uuid4(),
                    name="IC Government",
                    name_ar="مركز المعلومات الحكومي",
                    email=LIFESMART_EMAIL,
                    phone="+966-11-000-0000",
                    lifesmart_app_key=LIFESMART_APP_KEY,
                    lifesmart_app_token=LIFESMART_APP_TOKEN,
                    lifesmart_region=LIFESMART_REGION,
                    subscription_plan="enterprise",
                    max_devices=500,
                    max_sensors=1000,
                    max_users=50,
                    is_active=True,
                    is_subscription_active=True,
                )
                session.add(tenant)
                await session.flush()
                print(f"✅ Created tenant: {tenant.name}")
            
            # Connect to LifeSmart and authenticate
            print("\n🔗 Connecting to LifeSmart API...")
            client = LifeSmartClient(
                app_key=LIFESMART_APP_KEY,
                app_token=LIFESMART_APP_TOKEN,
                region=LIFESMART_REGION
            )
            
            # Authenticate
            auth_result = await client.authenticate(
                username=LIFESMART_EMAIL,
                password=LIFESMART_PASSWORD
            )
            
            if auth_result.success:
                print(f"✅ Authentication successful!")
                print(f"   User ID: {auth_result.user_id}")
                
                # Update tenant with user credentials
                tenant.lifesmart_user_id = auth_result.user_id
                tenant.lifesmart_user_token = auth_result.user_token
                
                # Fetch devices
                print("\n📱 Fetching devices from LifeSmart...")
                devices = await client.get_devices()
                print(f"✅ Found {len(devices)} devices")
                
                # Sync devices to database
                new_count = 0
                updated_count = 0
                
                for ls_device in devices:
                    # Check if device exists
                    result = await session.execute(
                        select(Device).where(
                            Device.tenant_id == tenant.id,
                            Device.lifesmart_device_id == ls_device.device_id
                        )
                    )
                    existing_device = result.scalar_one_or_none()
                    
                    if existing_device:
                        # Update existing device
                        existing_device.name = ls_device.name
                        existing_device.device_type = ls_device.device_type
                        existing_device.is_online = ls_device.is_online
                        existing_device.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()
                        }
                        existing_device.updated_at = datetime.utcnow()
                        updated_count += 1
                        print(f"   🔄 Updated: {ls_device.name} ({ls_device.device_type})")
                    else:
                        # Create new device
                        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,
                            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})")
                
                print(f"\n📊 Sync Summary:")
                print(f"   New devices: {new_count}")
                print(f"   Updated devices: {updated_count}")
                
                # Create smart alert rules
                print("\n🔔 Creating smart alert rules...")
                
                # Get all synced devices
                result = await session.execute(
                    select(Device).where(Device.tenant_id == tenant.id)
                )
                all_devices = result.scalars().all()
                
                alert_rules_created = 0
                
                for device in all_devices:
                    # Check if alert rule already exists
                    result = await session.execute(
                        select(AlertRule).where(
                            AlertRule.device_id == device.id
                        )
                    )
                    existing_rules = result.scalars().all()
                    
                    if existing_rules:
                        continue
                    
                    # Create alert rules based on device type
                    if device.device_type == "environment_sensor":
                        # High temperature alert
                        temp_rule = 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
                        )
                        session.add(temp_rule)
                        
                        # Low temperature alert
                        low_temp_rule = AlertRule(
                            id=uuid.uuid4(),
                            tenant_id=tenant.id,
                            device_id=device.id,
                            name=f"تنبيه انخفاض الحرارة - {device.name}",
                            name_ar=f"تنبيه انخفاض الحرارة - {device.name}",
                            condition_type="less_than",
                            threshold_value=15.0,
                            reading_type="temperature",
                            severity="info",
                            notification_channels=["email"],
                            is_active=True
                        )
                        session.add(low_temp_rule)
                        
                        # High humidity alert
                        humidity_rule = 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
                        )
                        session.add(humidity_rule)
                        alert_rules_created += 3
                        
                    elif device.device_type == "motion_sensor":
                        # Motion detected alert
                        motion_rule = 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
                        )
                        session.add(motion_rule)
                        alert_rules_created += 1
                        
                    elif device.device_type == "door_sensor":
                        # Door opened alert
                        door_rule = 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
                        )
                        session.add(door_rule)
                        alert_rules_created += 1
                        
                    elif device.device_type in ["gas_sensor", "smoke_sensor"]:
                        # Gas/Smoke detected alert (critical)
                        gas_rule = 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" if device.device_type == "gas_sensor" else "smoke_level",
                            severity="critical",
                            notification_channels=["email", "push", "sms"],
                            is_active=True
                        )
                        session.add(gas_rule)
                        alert_rules_created += 1
                        
                    elif device.device_type == "water_leak_sensor":
                        # Water leak alert (critical)
                        water_rule = 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
                        )
                        session.add(water_rule)
                        alert_rules_created += 1
                        
                    elif device.device_type == "door_lock":
                        # Unlock alert
                        unlock_rule = 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
                        )
                        session.add(unlock_rule)
                        alert_rules_created += 1
                    
                    # Device offline alert for all devices
                    offline_rule = 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
                    )
                    session.add(offline_rule)
                    alert_rules_created += 1
                
                print(f"✅ Created {alert_rules_created} alert rules")
                
                # Create admin user if not exists
                result = await session.execute(
                    select(User).where(User.email == LIFESMART_EMAIL)
                )
                existing_user = result.scalar_one_or_none()
                
                if not existing_user:
                    # Hash password
                    password_hash = hashlib.sha256(LIFESMART_PASSWORD.encode()).hexdigest()
                    
                    admin_user = User(
                        id=uuid.uuid4(),
                        tenant_id=tenant.id,
                        email=LIFESMART_EMAIL,
                        password_hash=password_hash,
                        full_name="IC IT Helpdesk",
                        full_name_ar="الدعم الفني IC",
                        role="tenant_admin",
                        is_active=True
                    )
                    session.add(admin_user)
                    print(f"✅ Created admin user: {LIFESMART_EMAIL}")
                else:
                    print(f"✅ Admin user already exists: {LIFESMART_EMAIL}")
                
                await session.commit()
                print("\n✅ All changes committed successfully!")
                
            else:
                print(f"❌ Authentication failed: {auth_result.error}")
                
            await client.close()
            
        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())
