"""
Simple script to add IC tenant with LifeSmart credentials
"""
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, text
from datetime import datetime
import uuid
import hashlib

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

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.database import Base
    
    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:
            # Check if tenant 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
                # Update LifeSmart credentials
                tenant.lifesmart_app_key = LIFESMART_APP_KEY
                tenant.lifesmart_app_token = LIFESMART_APP_TOKEN
                tenant.lifesmart_region = LIFESMART_REGION
            else:
                # Create 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)
                print(f"✅ Created tenant: IC Government")
            
            await session.flush()
            
            # Check if user 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 using bcrypt-like format
                password_hash = "$2b$12$" + hashlib.sha256(LIFESMART_PASSWORD.encode()).hexdigest()[:53]
                
                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")
            
            await session.commit()
            
            print(f"\n📋 Tenant Details:")
            print(f"   ID: {tenant.id}")
            print(f"   Name: {tenant.name}")
            print(f"   Email: {tenant.email}")
            print(f"   App Key: {LIFESMART_APP_KEY[:10]}...")
            print(f"   Region: {LIFESMART_REGION}")
            print(f"\n✅ Setup complete!")
            print(f"\n🔗 Next steps:")
            print(f"   1. Login to the dashboard with: {LIFESMART_EMAIL} / {LIFESMART_PASSWORD}")
            print(f"   2. Go to LifeSmart Integration page")
            print(f"   3. Connect with your LifeSmart credentials")
            print(f"   4. Sync devices")
            
        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())
