import json
import os
import sys
import requests

BASE_URL = os.getenv('SERVICEM8_BASE_URL', 'https://api.servicem8.com')
ENDPOINT = '/webhook_subscriptions/event'
ACCESS_TOKEN = os.getenv('SERVICEM8_ACCESS_TOKEN', 'smk-ac525b-99c4b96305a49c7c-fe4dd3e705b647ea')
EVENT_NAME = os.getenv('SERVICEM8_EVENT', 'form.response_created')
CALLBACK_URL = os.getenv('SERVICEM8_CALLBACK_URL', 'https://nps-dev.coast2cloud.net/webhooks/servicem8/form-response')
UNIQUE_ID = os.getenv('SERVICEM8_UNIQUE_ID', 'dev-form-response')


def pretty_print_json(data):
    print(json.dumps(data, indent=2, sort_keys=True))


def create_webhook():
    url = f"{BASE_URL}{ENDPOINT}"
    headers = {
        'X-API-Key': f'{ACCESS_TOKEN}',
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
    }
    form_data = {
        'event': EVENT_NAME,
        'callback_url': CALLBACK_URL,
        'unique_id': UNIQUE_ID,
    }

    response = requests.post(url, headers=headers, data=form_data, timeout=30)
    print(f'HTTP {response.status_code}')

    try:
        response_json = response.json()
        pretty_print_json(response_json)
    except ValueError:
        print('Response was not valid JSON:')
        print(response.text)
        sys.exit(1)

    if not response.ok:
        sys.exit(1)


if __name__ == '__main__':
    create_webhook()
