from typing import Tuple
from typing import List
import aiohttp
import json


async def _groups_memberships_list(
    access_token: str, group_parent: str
) -> Tuple[List[str], List[str]]:
    """Get a tuple of (group_emails, member_emails) in this group_parent"""
    members = []
    child_groups = []

    async with aiohttp.ClientSession() as session:
        page_token = None
        while True:
            # https://cloud.google.com/identity/docs/reference/rest/v1/groups/lookup
            # use view=FULL so we get the membership 'type' (GROUP or other)
            async with session.get(
                f'https://cloudidentity.googleapis.com/v1/{group_parent}/memberships?'
                f'view=FULL&pageToken={page_token or ""}',
                headers={'Authorization': f'Bearer {access_token}'},
            ) as resp:
                resp.raise_for_status()

                content = await resp.text()
                decoded = json.loads(content)

                for member in decoded['memberships']:
                    member_id = member['preferredMemberKey']['id']
                    if member['type'] == 'GROUP':
                        child_groups.append(member_id)
                    else:
                        members.append(member_id)

                page_token = decoded.get('nextPageToken')
                if not page_token:
                    break

    return child_groups, members