<commit_before># -*- coding: utf-8 -*-
import os
import json
import re

from scalrctl import defaults

__author__ = '<NAME>'


DOCS_HOST = 'http://api-explorer.scalr.com.s3-website-us-east-1.amazonaws.com'

EXCLUDES = [
    '/{envId}/farm-roles/{farmRoleId}/servers/',
    '/{envId}/servers/'
]

DEFAULTS = {
    'string': '',
    'boolean': True,
    'integer': 1,
    'array': []
}


def _read_spec(api_level, extension="json"):
    text = None
    spec_path = os.path.join(defaults.CONFIG_DIRECTORY,
                             '{}.{}'.format(api_level, extension))
    if os.path.exists(spec_path):
        with open(spec_path, "r") as fp:
            text = fp.read()
    return text


def _item_by_ref(spec_data, ref):
    _, _, definition = ref.strip('/').split('/')
    return spec_data['definitions'][definition]


def _generate_params(spec_data, schema):
    params = {}

    if '$ref' in schema:
        schema = _item_by_ref(spec_data, schema['$ref'])

    if 'properties' in schema:
        for p_key, p_value in schema['properties'].items():
            if '$ref' in p_value:
                sub_item = _item_by_ref(spec_data, p_value['$ref'])
                params[p_key] = _generate_params(spec_data, sub_item)
            else:
                if 'enum' in p_value:
                    params[p_key] = p_value['enum'][0]
                else:
                    params[p_key] = DEFAULTS[p_value['type']]

    return params


def generate_post_data(spec_data, endpoint):
    """
    Generates POST data for specified API endpoint.
    """

    if endpoint in spec_data['paths']:
        params_spec = spec_data['paths'].get(endpoint)
    else:
        raise Exception('API endpoint {} does not found'.format(endpoint))

    if 'post' in params_spec:
        if 'parameters' in params_spec['post']:
            schema = params_spec['post']['parameters'][0]['schema']
            post_data = _generate_params(spec_data, schema)
        else:
            post_data = {}
    else:
        raise Exception('POST method for endpoint {} does not exist'
                        .format(endpoint))

    return post_data


def get_definition(spec_data, endpoint):
    """
    Returns object name by endpoint.
    """

    if endpoint in spec_data['paths']:
        endpoint_spec = spec_data['paths'].get(endpoint)
    else:
        raise Exception('API endpoint {} does not found'.format(endpoint))

    params = endpoint_spec['post'].get('parameters', '')
    params = filter(lambda p: '$ref' in p.get('schema', ''), params)
    names = map(lambda p: p.get('schema')['$ref'].split('/')[-1], params)
    names = list(names)
    return names[0] if names else None


def get_doc_url(api_level, endpoint):<commit_msg>ST-169 Generate examples for POST methods<commit_after># -*- coding: utf-8 -*-
import os
import json
import re

from scalrctl import defaults

__author__ = '<NAME>'


DOCS_HOST = 'http://api-explorer.scalr.com.s3-website-us-east-1.amazonaws.com'

EXCLUDES = [
    '/{envId}/farm-roles/{farmRoleId}/servers/',
    '/{envId}/servers/'
]

DEFAULTS = {
    'string': '',
    'boolean': True,
    'integer': 1,
    'array': []
}


def _read_spec(api_level, extension="json"):
    text = None
    spec_path = os.path.join(defaults.CONFIG_DIRECTORY,
                             '{}.{}'.format(api_level, extension))
    if os.path.exists(spec_path):
        with open(spec_path, "r") as fp:
            text = fp.read()
    return text


def _item_by_ref(spec_data, ref):
    _, _, definition = ref.strip('/').split('/')
    return spec_data['definitions'][definition]


def _generate_params(spec_data, schema):
    params = {}

    if '$ref' in schema:
        schema = _item_by_ref(spec_data, schema['$ref'])

    if 'properties' in schema:
        for p_key, p_value in schema['properties'].items():
            if '$ref' in p_value:
                sub_item = _item_by_ref(spec_data, p_value['$ref'])
                params[p_key] = _generate_params(spec_data, sub_item)
            else:
                if 'enum' in p_value:
                    params[p_key] = p_value['enum'][0]
                else:
                    params[p_key] = DEFAULTS[p_value['type']]

    return params


def generate_post_data(spec_data, endpoint):
    """
    Generates POST data for specified API endpoint.
    """

    if endpoint in spec_data['paths']:
        params_spec = spec_data['paths'].get(endpoint)
    else:
        raise Exception('API endpoint {} does not found'.format(endpoint))

    if 'post' in params_spec:
        if 'parameters' in params_spec['post']:
            schema = params_spec['post']['parameters'][0]['schema']
            post_data = _generate_params(spec_data, schema)
        else:
            post_data = {}
    else:
        raise Exception('POST method for endpoint {} does not exist'
                        .format(endpoint))

    return post_data


def get_definition(spec_data, endpoint):
    """
    Returns object name by endpoint.
    """

    if endpoint in spec_data['paths']:
        endpoint_spec = spec_data['paths'].get(endpoint)
    else:
        raise Exception('API endpoint {} does not found'.format(endpoint))

    params = endpoint_spec['post'].get('parameters', '')
    params = filter(lambda p: '$ref' in p.get('schema', ''), params)
    names = list(map(lambda p: p.get('schema')['$ref'].split('/')[-1], params))
    return names[0] if names else None


def get_doc_url(api_level, endpoint):
{'fraction_non_alphanumeric': 0.1433284457478006, 'fraction_numerical': 0.0034824046920821114, 'mean_word_length': 2.599604221635884, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '73850', 'n_tokens_mistral': 1719, 'n_tokens_neox': 1685, 'n_words': 386}