#!/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.wildfly
from lib.globals import STATE_OK, STATE_UNKNOWN

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

DESCRIPTION = """Monitors non-XA datasource connection pool metrics on a WildFly/JBoss AS server via
its HTTP management API. Reports active, available, and idle connections. Alerts when
pool usage exceeds the configured thresholds."""

DEFAULT_CRIT = 90
DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 3
DEFAULT_URL = 'http://localhost:9990'
DEFAULT_USERNAME = 'wildfly-monitoring'
DEFAULT_WARN = 80


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(
        '--always-ok',
        help=lib.args.help('--always-ok'),
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--critical',
        help=lib.args.help('--critical') + ' Default: >= %(default)s',
        dest='CRIT',
        default=DEFAULT_CRIT,
    )

    parser.add_argument(
        '--datasource',
        help='Non-XA datasource name to check. '
        'Can be specified multiple times. '
        'If not specified, all non-XA datasources are checked.',
        dest='DATASOURCE',
        action='append',
        default=None,
    )

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

    parser.add_argument(
        '--instance',
        help='WildFly instance (server-config) to check when running in domain mode.',
        dest='INSTANCE',
    )

    parser.add_argument(
        '--mode',
        help='WildFly server mode. Default: %(default)s',
        dest='MODE',
        choices=['standalone', 'domain'],
        default='standalone',
    )

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

    parser.add_argument(
        '--node',
        help='WildFly node (host) when running in domain mode.',
        dest='NODE',
    )

    parser.add_argument(
        '-p',
        '--password',
        help='WildFly management API password.',
        dest='PASSWORD',
        required=True,
    )

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

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

    parser.add_argument(
        '--username',
        help='WildFly management API username. Default: %(default)s',
        dest='USERNAME',
        default=DEFAULT_USERNAME,
        required=True,
    )

    parser.add_argument(
        '--warning',
        help=lib.args.help('--warning') + ' Default: >= %(default)s',
        dest='WARN',
        default=DEFAULT_WARN,
    )

    args, _ = parser.parse_known_args()
    return args


def check_non_xa_datasource(args):
    data = {
        'operation': 'read-resource',
        'include-runtime': 'true',
        'recursive': 'true',
        # /subsystem/datasources/data-source/" + ds_name + "/statistics/pool/
        'address': [
            {'subsystem': 'datasources'},
            {'data-source': '*'},
            {'statistics': 'pool'},
        ],
        'json': 1,
    }
    res = lib.wildfly.get_data(args, data)


    # init some vars
    msg = ''
    perfdata = ''
    state = STATE_OK

    ds_stat_types = [
        'BlockingFailureCount',
        'CreatedCount',
        'DestroyedCount',
        'IdleCount',
        'InUseCount',
        'MaxWaitCount',
        'WaitCount',
        # 'XACommitCount',
        # 'XAEndCount',
        # 'XAForgetCount',
        # 'XAPrepareCount',
        # 'XARecoverCount',
        # 'XARollbackCount',
        # 'XAStartCount',
    ]

    for ds in res:
        name = ''
        # get the datasource name
        for v in ds['address']:
            if 'data-source' in v:
                name = v['data-source']
                break

        if args.DATASOURCE is not None:
            # filter for specific datasource
            if name not in args.DATASOURCE:
                continue

        available = int(ds['result']['AvailableCount'])
        if available == 0:

            # build the message
            msg += f'Statistics are not enabled for data source {name}; '
            continue

        msg += f'{name}: '

        active = int(ds['result']['ActiveCount'])
        max_used = int(ds['result']['MaxUsedCount'])
        if available != 0:
            active_pct = round(float(active) / float(available) * 100, 1)
            max_used_pct = round(float(max_used) / float(available) * 100, 1)
        else:
            active_pct = 0
            max_used_pct = 0

        local_state = lib.base.get_state(active_pct, args.WARN, args.CRIT)
        msg += f'{active_pct}% active used ({active}/{available}){lib.base.state2str(local_state, prefix=" ")}, '
        state = lib.base.get_worst(local_state, state)

        local_state = lib.base.get_state(max_used_pct, args.WARN, args.CRIT)
        msg += f'{max_used_pct}% max used ({max_used}/{available}){lib.base.state2str(local_state, prefix=" ")}, '
        state = lib.base.get_worst(local_state, state)

        perfdata += lib.base.get_perfdata(
            f'non-xa-ds-{name}-available',
            available,
            _min=0,
            _max=available,
        )
        perfdata += lib.base.get_perfdata(
            f'non-xa-ds-{name}-active',
            active,
            _min=0,
            _max=active,
        )
        perfdata += lib.base.get_perfdata(
            f'non-xa-ds-{name}-active-pct',
            active_pct,
            uom='%',
            warn=args.WARN,
            crit=args.CRIT,
            _min=0,
            _max=100,
        )
        perfdata += lib.base.get_perfdata(
            f'non-xa-ds-{name}-maxused',
            max_used,
            _min=0,
            _max=available,
        )
        perfdata += lib.base.get_perfdata(
            f'non-xa-ds-{name}-maxused-pct',
            max_used_pct,
            uom='%',
            warn=args.WARN,
            crit=args.CRIT,
            _min=0,
            _max=100,
        )

        for metric in ds_stat_types:
            if metric in ds['result']:
                if ds['result'][metric] > 0:
                    msg += f'{metric}={ds["result"][metric]}, '
                perfdata += lib.base.get_perfdata(
                    f'non-xa-ds-{name}-{metric.lower()}',
                    ds['result'][metric],
                    _min=0,
                )
        msg = msg[:-2] + '; '

    if msg:
        lib.base.oao(f'{msg[:-2]}', state, perfdata, always_ok=args.ALWAYS_OK)
    else:
        # over and out
        lib.base.oao('No datasources found.', state)


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
    # https://docs.wildfly.org/23/Admin_Guide.html
    return check_non_xa_datasource(args)


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