#!/usr/bin/env python3
"""
Reset admin password script.
Updates the hashed_password for superadmin@profibot.hu in the identity.users table.
Sets password to Admin123! using the system's get_password_hash function.
Ensures is_active is set to True.
"""

import asyncio
import sys
import os

# Add the backend directory to the Python path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from sqlalchemy import update, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import AsyncSessionLocal, engine
from app.models.identity.identity import User
from app.core.security import get_password_hash


async def reset_admin_password():
    """Reset password for superadmin@profibot.hu"""
    email = "superadmin@profibot.hu"
    new_password = "Admin123!"
    
    print(f"🔧 Resetting password for {email}...")
    
    async with AsyncSessionLocal() as session:
        # First, check if the user exists
        stmt = select(User).where(User.email == email)
        result = await session.execute(stmt)
        user = result.scalar_one_or_none()
        
        if not user:
            print(f"❌ User {email} not found in database!")
            return False
        
        print(f"✅ Found user: ID={user.id}, email={user.email}, is_active={user.is_active}")
        
        # Generate new password hash
        hashed_password = get_password_hash(new_password)
        print(f"🔐 Generated password hash: {hashed_password[:20]}...")
        
        # Update the user
        update_stmt = (
            update(User)
            .where(User.email == email)
            .values(
                hashed_password=hashed_password,
                is_active=True
            )
        )
        await session.execute(update_stmt)
        await session.commit()
        
        print(f"✅ Password updated successfully!")
        print(f"📋 New credentials:")
        print(f"   Email: {email}")
        print(f"   Password: {new_password}")
        print(f"   is_active: True")
        
        # Verify the update
        result = await session.execute(stmt)
        updated_user = result.scalar_one_or_none()
        if updated_user:
            print(f"✅ Verification: User is_active={updated_user.is_active}")
            if updated_user.hashed_password == hashed_password:
                print(f"✅ Password hash matches!")
            else:
                print(f"⚠️  Password hash mismatch (should not happen)")
        
        return True


async def main():
    try:
        success = await reset_admin_password()
        if success:
            print("\n🎉 Password reset completed successfully!")
            print("You can now log in with superadmin@profibot.hu / Admin123!")
            sys.exit(0)
        else:
            print("\n❌ Password reset failed!")
            sys.exit(1)
    except Exception as e:
        print(f"💥 Error during password reset: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


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