# Copyright (C) 2025 Axivion GmbH
# Copyright (C) 2025 The Qt Company GmbH, a subsidiary of The Qt Group
# https://www.qt.io
# pyright: standard


import typing

import requests

dashboard = 'http://localhost:9090/axivion'
project = 'purple'
auth = ('wjane', 'password')


def get_json(path, params=None) -> typing.Dict[str, typing.Any]:
    return requests.get(
        dashboard + path,
        auth=auth,
        headers={"Accept": 'application/json'},
        params=params or {},
    ).json()


# Same url as in dashboard when filtering for the provider "edg" and excluding issues with the tag False_Positive
json = get_json(
    '/api/projects/' + project + '/issues',
    {'kind': 'SV', 'filter_provider': '"edg"', 'filter_tags': '!"False_Positive"'},
)
some_issue = json["rows"][0]
print('Severity: %s' % some_issue["severity"])
print('Error Number: %s' % some_issue["errorNumber"])
print('Path: %s' % some_issue["path"])
print('Message: %s' % some_issue["message"])

# If we're only interested in the count we can use &limit=0&computeTotalRowCount=true to not actually query the issue data
# and have some numbers sent over instead
json = get_json(
    '/api/projects/' + project + '/issues',
    {
        'kind': 'SV',
        'filter_provider': '"edg"',
        'filter_tags': '!"False_Positive"',
        'limit': '0',
        'computeTotalRowCount': 'true',
    },
)
print(json["totalRowCount"])

# For a diff between the two most recent analyzed versions we insert &start=-1&end=now
json = get_json(
    '/api/projects/' + project + '/issues',
    {
        'kind': 'SV',
        'filter_provider': '"edg"',
        'filter_tags': '!"False_Positive"',
        'start': '-1',
        'end': 'latest',
        'limit': '0',
        'computeTotalRowCount': 'true',
    },
)
print(json["totalRowCount"])
print(json["totalAddedCount"])
print(json["totalRemovedCount"])

# For doing some statistics we could do something that involves more than just one query
# Query information we'll later use to make more specific queries on the project issues
project_json = get_json('/api/projects/' + project)

for user in project_json["users"]:
    for version in project_json["versions"]:
        for issueKind in project_json["issueKinds"]:
            json = get_json(
                '/api/projects/' + project + '/issues',
                {
                    'user': user['name'],
                    'version': version['index'],
                    'kind': issueKind['prefix'],
                    'limit': '0',
                    'computeTotalRowCount': 'true',
                },
            )
            print(
                '%s of %s in version %s: %s'
                % (
                    issueKind['nicePluralName'],
                    user['displayName'],
                    version['name'],
                    json['totalRowCount'],
                )
            )

# If we want to do some state-changing things like creating, editing or deleting objects,
# we need a so-called CSRF-Token first and send it along with the state-changing request.
api_info = get_json('/api', params={'exclude_project_info': 'true'})
# (set the request parameter `exclude_project_info` to `true` to save server resources
# and, as a result, enhance request performance; defaults to `false` for compatibility
# reasons)

csrfTokenHeader = api_info['csrfTokenHeader']
csrfToken = api_info['csrfToken']

# Note that we send along the same authentication credentials as we did when getting
# the api info as well as an additional request header whose name we also get from
# the api info.
requests.put(
    dashboard + '/api/projects/' + project + '/issues/SV123/tags/MY_NEW_TAG/',
    auth=auth,
    headers={"Accept": 'application/json', csrfTokenHeader: csrfToken},
)
