#!/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 json
import sys

import lib.args
import lib.base
import lib.lftest
import lib.time
import lib.url
from lib.globals import STATE_CRIT, STATE_OK, STATE_UNKNOWN, STATE_WARN

__author__ = """Linuxfabrik GmbH, Zurich/Switzerland;
                originally written by Dominik Riva, Universitätsspital Basel/Switzerland"""
__version__ = '2026050801'


DESCRIPTION = """Monitors the SAP Concur Open status page (open.concur.com) for active service
incidents. Alerts when unresolved incidents are reported on the dashboard."""

DEFAULT_DATACENTER = 'eu2'
DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_SERVICE = 'All'
DEFAULT_TIMEOUT = 8
DEFAULT_UTC_OFFSET = lib.time.utc_offset()

services = [
    'Analysis/Intelligence',
    'Compleat (TMC Services)',
    'Expense',
    'Imaging',
    'Invoice',
    'Mobile',
    'Request',
    'Travel',
]


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

    parser.add_argument(
        '--always-ok',
        help=lib.args.help('--always-ok'),
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

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

    parser.add_argument(
        '--datacenter',
        help='SAP Concur datacenter to query. Default: %(default)s',
        dest='DATACENTER',
        default=DEFAULT_DATACENTER,
        choices=[
            'us',
            'us2',
            'eu',
            'eu2',
            'cn',
            'pscc',
        ],
        required=True,
    )

    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(
        '--service',
        help='SAP Concur service to check. '
        'One of "Analysis/Intelligence", "Compleat (TMC Services)", "Expense", '
        '"Imaging", "Invoice", "Mobile", "Request", "Travel", or simply "All". '
        'Check https://open.concur.com to see which service is available for which datacenter. '
        'Default: %(default)s',
        dest='SERVICE',
        default=DEFAULT_SERVICE,
        choices=[*services, 'All'],
    )

    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(
        '--utc-offset',
        help='UTC offset for timestamp display. Default: %(default)s',
        dest='UTC_OFFSET',
        default=DEFAULT_UTC_OFFSET,
    )

    args, _ = parser.parse_known_args()
    return args


def get_state(concur_status):
    """Translates SAP status from open.concur.com to Nagios state."""
    if concur_status == 'normal':
        return STATE_OK
    if concur_status == 'degradation':
        return STATE_WARN
    if concur_status == 'disruption':
        return STATE_CRIT
    return STATE_UNKNOWN


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:
        url = (
            f'https://open.concur.com/api/v2/status_history'
            f'?data_center={args.DATACENTER}'
            f'&utc_offset={args.UTC_OFFSET}'
        )
        result = lib.base.coe(
            lib.url.fetch_json(
                url,
                insecure=args.INSECURE,
                no_proxy=args.NO_PROXY,
                timeout=args.TIMEOUT,
            )
        )
    else:
        # do not call the command, put in test data
        stdout, _stderr, _retc = lib.lftest.test(args.TEST)
        result = json.loads(stdout)

    if args.SERVICE == 'All':
        state = STATE_OK

        # init some vars
        msg = ''
        for service in services:
            try:
                status = result['data'][service]['Current Status']['status']
            except KeyError:
                # Not all datacenters offer all services
                continue
            if status != 'normal':
                local_state = get_state(status)
                state = lib.base.get_worst(state, local_state)

                # build the message
                msg += f'{service}: {status}{lib.base.state2str(local_state, prefix=" ")}, '
        msg = 'Everything is ok.' if msg == '' else msg[:-2]
    else:
        try:
            status = result['data'][args.SERVICE]['Current Status']['status']
        except KeyError:
            lib.base.oao(
                f'No result for {args.SERVICE}@{args.DATACENTER}.', STATE_UNKNOWN
            )
        msg = f'{args.SERVICE}: {status}'
        state = get_state(status)

    msg += f' (@{args.DATACENTER}, UTC{args.UTC_OFFSET})'

    # over and out
    lib.base.oao(msg, state, always_ok=args.ALWAYS_OK)


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