import json
import os
import sys
import requests

BASE_URL = os.getenv('SERVICEM8_BASE_URL', 'https://api.servicem8.com')
ENDPOINT = '/webhook_subscriptions'
ACCESS_TOKEN = os.getenv('SERVICEM8_ACCESS_TOKEN', 'smk-ac525b-99c4b96305a49c7c-fe4dd3e705b647ea')
OBJECT_NAME = os.getenv('SERVICEM8_OBJECT', 'job')
FIELDS = os.getenv('SERVICEM8_FIELDS', 'uuid,status,date,queue_uuid,queue_expiry_date,work_order_date,active,edit_date,generated_job_id')
CALLBACK_URL = os.getenv('SERVICEM8_CALLBACK_URL', 'https://nps-dev.coast2cloud.net/webhooks/servicem8-object')
UNIQUE_ID = os.getenv('SERVICEM8_UNIQUE_ID', 'dev-job-object')


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


def parse_fields(value):
    return [field.strip() for field in value.split(',') if field.strip()]


def create_webhook():
    if not ACCESS_TOKEN:
        print('SERVICEM8_ACCESS_TOKEN is required')
        sys.exit(1)

    fields = parse_fields(FIELDS)
    if not fields:
        print('SERVICEM8_FIELDS must contain at least one field')
        sys.exit(1)

    url = f"{BASE_URL}{ENDPOINT}"
    headers = {
        'X-API-Key': ACCESS_TOKEN,
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
    }
    form_data = [
       ('type', 'object'),
       ('object', OBJECT_NAME),
       ('callback_url', CALLBACK_URL),
       ('unique_id', UNIQUE_ID),
    ]

    for field in fields:
        form_data.append(('fields', field))

    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()
