<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def register_device(ctx, device, model, nickname, client_type):
 """Registers a device instance under an existing device model. Device instance fields must start with a letter or number. The device ID can only contain letters, numbers, and the following symbols: period (.), hyphen (-), underscore (_), and plus (+). The device nickname can only contain numbers, letters, and the space ( ) symbol. """

    session, api_url, project_id = build_client_from_context(ctx)
    device_base_url = '/'.join([api_url, 'devices'])
    device_url = '/'.join([device_base_url, device])
    payload = {
        'id': device,
        'model_id': model,
    }
    if client_type:
        payload['client_type'] = 'SDK_' + client_type
    if nickname:
        payload['nickname'] = nickname

    logging.debug(json.dumps(payload))
    r = session.get(device_url)
    if r.status_code == 200:
        click.echo('Updating existing device: %s' % device)
        session.delete(device_url)
        r = session.post(device_base_url, data=json.dumps(payload))
    elif r.status_code in (400, 403, 404):
        click.echo('Creating new device')
        r = session.post(device_base_url, data=json.dumps(payload))
    else:
        raise failed_request_exception('Failed to check existing device', r)
    if r.status_code != 200:
        raise failed_request_exception('Failed to register device', r)
    click.echo('Device instance %s successfully registered' % device)
    logging.debug(r.text)