"""
إضافة عمود alert_cooldown_minutes وتحديث إعدادات SMTP
"""
import asyncio
import sys
sys.path.insert(0, '.')

async def fix_database():
    from sqlalchemy import text
    from app.database import engine
    
    async with engine.begin() as conn:
        # إضافة العمود الجديد
        try:
            await conn.execute(text(
                "ALTER TABLE tenant_settings ADD COLUMN alert_cooldown_minutes INT DEFAULT 15"
            ))
            print("✓ Added alert_cooldown_minutes column")
        except Exception as e:
            if "Duplicate column" in str(e):
                print("Column alert_cooldown_minutes already exists")
            else:
                print(f"Error adding column: {e}")
        
        # تحديث كلمة مرور SMTP
        try:
            result = await conn.execute(text(
                "UPDATE tenant_settings SET smtp_password = 'ithelpdesk@123', smtp_enabled = 1 WHERE smtp_username = 'ithelpdesk@ai4ksa.com'"
            ))
            print(f"✓ Updated SMTP settings for {result.rowcount} tenant(s)")
        except Exception as e:
            print(f"Error updating SMTP: {e}")
        
        # عرض الإعدادات الحالية
        result = await conn.execute(text(
            "SELECT tenant_id, smtp_enabled, smtp_host, smtp_username, smtp_password FROM tenant_settings"
        ))
        rows = result.fetchall()
        print(f"\nCurrent settings ({len(rows)} tenants):")
        for row in rows:
            print(f"  Tenant: {row[0]}")
            print(f"    SMTP Enabled: {row[1]}")
            print(f"    Host: {row[2]}")
            print(f"    Username: {row[3]}")
            print(f"    Password: {'*' * len(row[4]) if row[4] else 'NOT SET'}")

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