import urllib.request
import json
import ssl

def get_vertexdc_users_via_api():
    api_url = "https://api.sibu.vertexdc.com"
    # Admin credentials the user gave me
    login_data = json.dumps({
        "email": "admin@sibu.com",
        "password": "admin",
        "keep_session": True
    }).encode('utf-8')
    
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    print(f"Attempting login to {api_url}/api/auth/login...")
    try:
        req = urllib.request.Request(f"{api_url}/api/auth/login", data=login_data, headers={'Content-Type': 'application/json'})
        with urllib.request.urlopen(req, context=ctx) as response:
            token_data = json.loads(response.read().decode('utf-8'))
            token = token_data.get("access_token")
            print("Login successful!")
        
        headers = {"Authorization": f"Bearer {token}"}
        
        # Try different search terms to find users
        search_terms = ["@", ".com", "admin", "promo", "usuario"]
        all_users = {}
        
        for term in search_terms:
            print(f"Searching for users matching '{term}'...")
            search_url = f"{api_url}/api/users/search?email={term}"
            req_search = urllib.request.Request(search_url, headers=headers)
            try:
                with urllib.request.urlopen(req_search, context=ctx) as response:
                    users = json.loads(response.read().decode('utf-8'))
                    for u in users:
                        all_users[u['email']] = u
            except Exception as e:
                print(f"Search for '{term}' failed: {e}")
        
        if all_users:
            print(f"\n✅ Found {len(all_users)} users on VertexDC:")
            for email, u in all_users.items():
                print(f"- {u['full_name']} ({email}) [Role: {u['role']}]")
        else:
            print("\n❌ No users found via API search.")
                
    except Exception as e:
        print(f"Critical error: {e}")

if __name__ == "__main__":
    get_vertexdc_users_via_api()
