"""
Script to fix user property structure in Firebase
Converts property from list format to dictionary format

Usage:
    python scripts/fix_user_property_structure.py
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from firebase.firebase import Firebase

fb = Firebase(host=os.environ.get("FIREBASE_HOST"))

def fix_user_property(user_id):
    """
    Fix property structure for a specific user
    Converts from list to dictionary format
    """
    user = fb.get_by_child(f"users/{user_id}")
    
    if not user:
        print(f"User {user_id} not found")
        return False
    
    if "property" not in user:
        print(f"User {user_id} has no property field")
        return False
    
    # Check if property is a list (needs fixing)
    if isinstance(user['property'], list):
        print(f"Fixing user {user_id}: property is a list, converting to dict...")
        
        property_dict = {}
        for property_id in user['property']:
            # Check if property exists in property collection
            property_data = fb.get_by_child(f"property/{property_id}")
            if property_data:
                # Try to get existing role/features from old structure
                # If not exists, set default
                property_dict[property_id] = {
                    "role": "user"  # Default role, adjust as needed
                }
                print(f"  - Added property {property_id}")
            else:
                print(f"  - Warning: Property {property_id} not found in property collection")
        
        # Update Firebase
        fb.db.reference().child(f"users/{user_id}/property").set(property_dict)
        print(f"✓ Fixed user {user_id}")
        return True
    else:
        print(f"User {user_id}: property is already a dictionary (no fix needed)")
        return False

def fix_all_users():
    """
    Fix property structure for all users
    """
    users = fb.get_by_child("users/")
    
    if not users:
        print("No users found")
        return
    
    fixed_count = 0
    for user_id in users.keys():
        if fix_user_property(user_id):
            fixed_count += 1
    
    print(f"\n✓ Fixed {fixed_count} users")

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='Fix user property structure in Firebase')
    parser.add_argument('--user-id', type=str, help='Fix specific user ID only')
    parser.add_argument('--all', action='store_true', help='Fix all users')
    
    args = parser.parse_args()
    
    if args.user_id:
        fix_user_property(args.user_id)
    elif args.all:
        fix_all_users()
    else:
        print("Please specify --user-id <id> or --all")
        print("Example: python scripts/fix_user_property_structure.py --user-id 123456")
        print("Example: python scripts/fix_user_property_structure.py --all")

