#!/usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author:  Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
#          https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.

# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.md

"""See the check's README for more details."""

import argparse
import sys

import lib.args
import lib.base
import lib.human
import lib.lftest
import lib.nodebb
import lib.time
from lib.globals import STATE_OK, STATE_UNKNOWN

__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026040801'

DESCRIPTION = """Monitors NodeBB group statistics via the admin API, including group count and
membership numbers."""

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 3
DEFAULT_URL = 'http://localhost:4567/forum'


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(description=DESCRIPTION)

    parser.add_argument(
        '-V',
        '--version',
        action='version',
        version=f'%(prog)s: v{__version__} by {__author__}',
    )

    parser.add_argument(
        '--insecure',
        help=lib.args.help('--insecure'),
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--no-proxy',
        help=lib.args.help('--no-proxy'),
        dest='NO_PROXY',
        action='store_true',
        default=DEFAULT_NO_PROXY,
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    parser.add_argument(
        '--timeout',
        help=lib.args.help('--timeout') + ' Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    parser.add_argument(
        '-p',
        '--token',
        help='NodeBB API bearer token.',
        dest='TOKEN',
        required=True,
    )

    parser.add_argument(
        '--url',
        help='NodeBB API URL. Default: %(default)s',
        dest='URL',
        default=DEFAULT_URL,
    )

    args, _ = parser.parse_known_args()
    return args


def main():
    """The main function. This is where the magic happens."""

    # parse the command line
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    # fetch data
    if args.TEST is None:
        result = lib.nodebb.get_data(args, '/api/admin/settings/post')
    else:
        # do not call the command, put in test data
        import json

        stdout, _stderr, _retc = lib.lftest.test(args.TEST)
        result = json.loads(stdout)

    # init some vars
    msg = ''
    perfdata = ''
    table_data = []

    # analyze data
    for post in result['groupsExemptFromPostQueue']:
        post['createtime'] = post['createtime'] / 1000
        post['createtimeiso'] = (
            f'{lib.time.epoch2iso(post["createtime"])}'
            f' ({lib.human.seconds2human(lib.time.now(as_type="epoch") - post["createtime"])} ago)'
        )
        table_data.append(post)

    # build the message
    group_count = len(result['groupsExemptFromPostQueue'])
    msg += f'{group_count} {lib.txt.pluralize("group", group_count)}'
    try:
        grp = result['groupsExemptFromPostQueue'][0]
        visibility = 'private' if grp['private'] else 'public'
        msg += (
            f', newest group: "{grp["name"]}"'
            f' ({visibility})'
            f' with {grp["memberCount"]} members'
            f' (created {grp["createtimeiso"]} ago)'
        )
    except Exception:
        pass
    msg += '\n\n'

    perfdata += lib.base.get_perfdata(
        'posts',
        len(result['groupsExemptFromPostQueue']),
        _min=0,
    )

    if table_data:
        keys = [
            'createtimeiso',
            'slug',
            'memberCount',
        ]
        headers = [
            'createtime',
            'slug',
            'memberCount',
        ]
        msg += lib.base.get_table(table_data, keys, header=headers)

    # over and out
    lib.base.oao(msg, STATE_OK, perfdata)


if __name__ == '__main__':
    try:
        main()
    except Exception:
        lib.base.cu()
