import demistomock as demisto
from CommonServerPython import *
import json


def parse_vulnerability(raw_json):
    data = json.loads(raw_json)

    if data.get('kind') != 'vulnerability':
        raise ValueError(f'Input should be a raw JSON vulnerability alert, received: {raw_json}')

    outputs = {'PrismaCloudCompute.VulnerabilityAlert': data}

    # remove unneeded fields from human readable results
    headers: list = []
    for field in data.keys():
        if field not in ['_id', 'kind', 'vulnerabilities']:
            headers.append(field)
    headers.sort()

    readable_outputs = tableToMarkdown('Vulnerability Information',
                                       data,
                                       headers=headers)

    # add another table for vulnerabilities
    readable_outputs += tableToMarkdown('Vulnerabilities', data.get('vulnerabilities'))

    return (
        readable_outputs,
        outputs,
        raw_json
    )


def main():
    try:
        return_outputs(*parse_vulnerability(demisto.args().get('alert_raw_json', '')))
    except Exception as ex:
        return_error(f'Failed to execute PrismaCloudComputeParseVulnerabilityAlert. Error: {str(ex)}')


if __name__ in ('__builtin__', 'builtins'):
    main()
