"""
Script to delete ALL users from the database ONLY
WARNING: This will delete users and their notification preferences
Use this in combination with clear_database_keep_users.py:
  1. Run clear_database_keep_users.py first to clean data
  2. Then run this to remove users
"""
from app import create_app
from app.extensions import db
from app.models import User
from app.models.notification import NotificationPreference

app = create_app()

with app.app_context():
    print("="*70)
    print("DELETE ALL USERS")
    print("="*70)
    
    user_count = User.query.count()
    pref_count = NotificationPreference.query.count()
    
    if user_count == 0:
        print("\n✅ No users in database")
        exit()
    
    print(f"\n👥 Current users in database: {user_count}")
    if pref_count > 0:
        print(f"📋 Notification preferences to delete: {pref_count}")
    
    print("\n⚠️  WARNING: This will delete ALL user accounts!")
    print("This will delete:")
    print("  - All user accounts (contractors, workers, admins)")
    print("  - All notification preferences")
    print("\n💡 TIP: Run clear_database_keep_users.py first to clean other data safely")
    
    print("\n" + "="*70)
    confirm = input("Type 'DELETE' to confirm: ")
    
    if confirm != 'DELETE':
        print("❌ Operation cancelled")
        exit()
    
    try:
        print("\n🗑️  Deleting all users...\n")
        
        # Delete notification preferences first (they reference users)
        if pref_count > 0:
            deleted_prefs = NotificationPreference.query.delete()
            if deleted_prefs:
                print(f"  ✓ Deleted {deleted_prefs} notification preference(s)")
        
        # Delete all users
        deleted = User.query.delete()
        
        # Commit deletion
        db.session.commit()
        
        print(f"  ✓ Deleted {deleted} user(s)")
        
        print("\n" + "="*70)
        print("✅ ALL USERS DELETED SUCCESSFULLY!")
        print("="*70)
        
        # Final verification
        remaining_users = User.query.count()
        
        if remaining_users == 0:
            print("\n  ✅ No users remaining in database")
        else:
            print(f"\n  ⚠️  {remaining_users} users still in database")
        
    except Exception as e:
        db.session.rollback()
        print(f"\n❌ Error during deletion: {str(e)}")
        import traceback
        traceback.print_exc()
        print("\n⚠️  Database rolled back - no changes made")
        print("\n💡 TIP: Try running clear_database_keep_users.py first to remove related data")
