"""
Utility script to fix existing users by ensuring their default location
is marked as accessible in their locationSettings.
"""

import json
import os

# Get the directory where this script is located
basedir = os.path.abspath(os.path.dirname(__file__))
USERS_FILE = os.path.join(basedir, '..', 'data', 'users.json')

def fix_default_locations():
    """
    Ensure all users have their default location marked as accessible.
    """
    if not os.path.exists(USERS_FILE):
        print("No users.json file found.")
        return
    
    # Load users
    with open(USERS_FILE, 'r') as f:
        users = json.load(f)
    
    print(f"Found {len(users)} users to check...")
    
    changes_made = 0
    for user in users:
        username = user.get('username', 'Unknown')
        default_location = user.get('defaultLocation')
        
        if not default_location:
            print(f"⚠️  User '{username}' has no default location - skipping")
            continue
        
        location_settings = user.get('locationSettings', {})
        
        # Check if default location is in settings and accessible
        if default_location not in location_settings:
            print(f"✓ Adding default location '{default_location}' for user '{username}'")
            location_settings[default_location] = {'accessible': True}
            user['locationSettings'] = location_settings
            changes_made += 1
        elif not location_settings[default_location].get('accessible', False):
            print(f"✓ Marking default location '{default_location}' as accessible for user '{username}'")
            location_settings[default_location]['accessible'] = True
            changes_made += 1
        else:
            print(f"  User '{username}' - default location already accessible")
    
    if changes_made > 0:
        # Save updated users
        with open(USERS_FILE, 'w') as f:
            json.dump(users, f, indent=2)
        print(f"\n✓ Fixed {changes_made} user(s) and saved to users.json")
    else:
        print("\n✓ All users already have correct default location settings")

if __name__ == '__main__':
    print("=" * 60)
    print("DEFAULT LOCATION FIX UTILITY")
    print("=" * 60)
    print()
    fix_default_locations()
    print()
