"""
Script to update user names in the database for proper audit trail display.
"""
from app.core.database import SessionLocal
from app.models.user import User

def update_user_names():
    """Update user first and last names for proper audit trail."""
    db = SessionLocal()
    try:
        print("=" * 70)
        print("USER NAME UPDATE SCRIPT")
        print("=" * 70)
        print()

        # Get all users
        users = db.query(User).all()
        print(f"Found {len(users)} users in the database\n")

        # Display current users
        print("Current Users:")
        print("-" * 70)
        for i, user in enumerate(users, 1):
            print(f"{i}. Username: {user.username:15} | First: {user.first_name or 'NULL':15} | Last: {user.last_name or 'NULL':15} | Role: {user.role}")
        print()

        # Prompt for updates
        print("Enter new names for each user (press Enter to skip):")
        print("-" * 70)

        updates = []
        for user in users:
            print(f"\nUser: {user.username} ({user.role})")
            first_name = input(f"  First Name [{user.first_name}]: ").strip()
            last_name = input(f"  Last Name [{user.last_name}]: ").strip()

            if first_name or last_name:
                updates.append({
                    'user': user,
                    'first_name': first_name or user.first_name,
                    'last_name': last_name or user.last_name
                })

        if not updates:
            print("\nNo changes requested. Exiting.")
            return

        # Confirm changes
        print("\n" + "=" * 70)
        print("PROPOSED CHANGES:")
        print("=" * 70)
        for upd in updates:
            user = upd['user']
            print(f"\n{user.username}:")
            print(f"  First Name: {user.first_name} → {upd['first_name']}")
            print(f"  Last Name:  {user.last_name} → {upd['last_name']}")

        confirm = input("\nApply these changes? (yes/no): ").strip().lower()

        if confirm == 'yes':
            for upd in updates:
                user = upd['user']
                user.first_name = upd['first_name']
                user.last_name = upd['last_name']

            db.commit()
            print("\n✓ Changes applied successfully!")

            # Display updated users
            print("\n" + "=" * 70)
            print("UPDATED USERS:")
            print("=" * 70)
            for user in db.query(User).all():
                print(f"Username: {user.username:15} | Name: {user.first_name} {user.last_name} | Role: {user.role}")
        else:
            print("\n✗ Changes cancelled.")

    except Exception as e:
        print(f"\n❌ Error: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    update_user_names()
