# One read-only CRM sync page. Python 3; no dependencies or network call on import.
# Pass api.request from MereuClient. commit_page must atomically persist data/checkpoint.
def sync_mereu_page(request, resource, state, commit_page, limit=100):
    if resource not in ('customers', 'cards', 'transactions'):
        raise ValueError('Unknown dataset')
    position = {'phase': 'snapshot', 'cursor': None} if state is None else state
    phase, cursor = position.get('phase'), position.get('cursor')
    if (phase not in ('snapshot', 'changes') or
            (cursor is not None and not isinstance(cursor, str)) or
            (phase == 'changes' and not cursor)):
        raise ValueError('Invalid local checkpoint')
    query = {'mode': phase, 'limit': limit}
    if cursor is not None:
        query['cursor'] = cursor
    page = request('GET', '/data/' + resource, query=query)
    if (page.get('mode') != phase or not isinstance(page.get('data'), list) or
            'next_cursor' not in page or
            (page['next_cursor'] is not None and not isinstance(page['next_cursor'], str)) or
            not isinstance(page.get('sync_cursor'), str)):
        raise ValueError('Invalid sync response')
    complete = page['next_cursor'] is None
    checkpoint = {'phase': 'changes' if complete else phase,
                  'cursor': page['sync_cursor'] if complete else page['next_cursor']}
    commit_page({'resource': resource, 'mode': phase,
                 'reset': phase == 'snapshot' and cursor is None,
                 'complete': complete, 'data': page['data'], 'checkpoint': checkpoint})
    return checkpoint

# Rename the downloaded modules to mereu_client.py and crm_sync.py when importing:
# from mereu_client import MereuClient
# from crm_sync import sync_mereu_page
# api = MereuClient(os.environ['MEREU_API_URL'], os.environ['MEREU_API_KEY'])
# state = your_database.read_checkpoint('customers')
# sync_mereu_page(api.request, 'customers', state, commit_page_in_one_transaction)
# Snapshot pages go to staging; swap at complete. Changes upsert/delete by record id.
# Persist the checkpoint in the SAME transaction. Process pages sequentially.
# On 410, rebuild from a new snapshot (state=None); do not rotate the API key for a cursor error.
