import demistomock as demisto  # noqa: F401
from CommonServerPython import *  # noqa: F401

ctx = demisto.context()
dataFromCtx = ctx.get("widgets")
if not dataFromCtx:
    incident = demisto.incidents()[0]
    accountName = incident.get('account')
    accountName = f"acc_{accountName}" if accountName != "" else ""

    stats = demisto.executeCommand(
        "demisto-api-post",
        {
            "uri": f"{accountName}/statistics/widgets/query",
            "body": {
                "size": 13,
                "dataType": "incidents",
                "query": "",
                "dateRange": {
                    "period": {
                        "byFrom": "months",
                        "fromValue": 12
                    }
                },
                "widgetType": "line",
                "params": {
                    "groupBy": [
                        "occurred(m)",
                        "null"
                    ],
                    "timeFrame": "months"
                },
            },
        })

    res = stats[0]["Contents"]["response"]

    buildNumber = demisto.executeCommand("DemistoVersion", {})[0]['Contents']['DemistoVersion']['buildNumber']
    buildNumber = f'{buildNumber}' if buildNumber != "REPLACE_THIS_WITH_CI_BUILD_NUM" else "618658"

    if int(buildNumber) >= 618657:
        # Line graph:
        data = {
            "Type": 17,
            "ContentsFormat": "line",
            "Contents": {
                "stats": res,
                "params": {
                    "timeFrame": "months"
                }
            }
        }

    else:
        # Bar graph:
        output = []
        for entry in res:
            output.append({"name": entry["name"], "data": entry["data"]})

        data = {
            "Type": 17,
            "ContentsFormat": "bar",
            "Contents": {
                "stats": output,
                "params": {
                    "layout": "horizontal"
                }
            }
        }

    demisto.results(data)
else:
    data = {
        "Type": 17,
        "ContentsFormat": "line",
        "Contents": {
            "stats": dataFromCtx['IncidentsCreatedMonthly'],
            "params": {
                "timeFrame": "months"
            }
        }
    }
    demisto.results(data)

[(4, 'demistomock.context', 'demisto.context', True, 'import demistomock as demisto\n'), (11, 'demistomock.executeCommand', 'demisto.executeCommand', True, 'import demistomock as demisto\n'), (71, 'demistomock.results', 'demisto.results', True, 'import demistomock as demisto\n'), (83, 'demistomock.results', 'demisto.results', True, 'import demistomock as demisto\n'), (7, 'demistomock.incidents', 'demisto.incidents', True, 'import demistomock as demisto\n'), (38, 'demistomock.executeCommand', 'demisto.executeCommand', True, 'import demistomock as demisto\n')]