#!/usr/local/bin/python3.14 -u
# SPDX-License-Identifier: AGPL-3.0-only

from collections import defaultdict
from datetime import datetime

import kopano

"""

provides an easy-to read overview of the kopano-server cache statistics,
as compared to the more low-level "kopano-stats --system"

"""

options, _ = kopano.parser('ksp').parse_args()
server = kopano.server(options=options, auth_user='SYSTEM', auth_pass='')

cstat = defaultdict(dict)
for name, value in server.stats().items():
    if name == 'server_start_date':
        serverstarttime = value

    # Skip non cache items
    if not name.startswith('cache_'):
        continue

    if name.endswith('_hit'):
        name = name[6:-4]
        cstat[name]['hits'] = int(value)
    if name.endswith('_req'):
        name = name[6:-4]
        cstat[name]['requests'] = int(value)
    if name.endswith('_size'):
        name = name[6:-5]
        cstat[name]['size'] = int(value)
    if name.endswith('_maxsz'):
        name = name[6:-6]
        cstat[name]['maxsz'] = int(value)

print('Kopano Cache Statistics')
print('  Server start time: %s' % (serverstarttime))
print('  Current time     : %s' % (datetime.now().strftime('%c')))
print('')
print('%10s %24s         %24s' % ('Cache', 'Hit ratio', 'Mem usage ratio'))

for name, data in cstat.items():
    if data['requests']:
        percentage = '%d%%' % (data['hits'] * 100 / data['requests'])
    else:
        percentage = 'N/A'

    if data['maxsz']:
        persize = '%d%%' % (data['size'] * 100 / data['maxsz'])
    else:
        persize = 'N/A'

    print('%10s (%12d/%12d) (%3s)   (%12d/%12d) (%3s)' % (name, data['hits'], data['requests'], percentage, data['size'], data['maxsz'], persize))
