#!/usr/bin/python3
# pylint: disable=consider-using-f-string
# pylint: disable=fixme
"""
 saphana_sr_tools.py
 Author:       Fabian Herschel, May 2023
 License:      GNU General Public License (GPL)
 Copyright:    (c) 2023-2025 SUSE LLC

# TODO: STEP02: Think also about multi SID implementation - maybe by using multiple HanaCluster objects (one per SID)
"""

#global TOOL_VERSION
TOOL_VERSION = "1.0.20250207"
# TODO pylint's constant vs variable detection is broken
# pylint: disable=invalid-name

# pylint: disable=wrong-import-position
# pylint: disable=unused-import
import argparse
import json
import os
import re
import sys
from dateutil import parser as dateutil_parser
sys.path.insert(1, '/usr/lib/SAPHanaSR-angi')
from saphana_sr_tools import HanaCluster,HanaStatus
# pylint: enable=wrong-import-position
# pylint: enable=unused-import

if __name__ == "__main__":
    myCluster = HanaCluster()
    parser = argparse.ArgumentParser()
    parser.add_argument("--cib", nargs="*", help="specify the cibfile file")
    parser.add_argument("--format", help="output format ([table], path, script, json)")
    parser.add_argument("--from", help="select 'from' - timepoint ('YYYY-M-D H:M:S')")
    parser.add_argument("--properties", help="specify the properties file")
    parser.add_argument("--experimental_attributes", help="experimental only - might be delated later; global:attr1,attr2 site:attr3,attr3 host:attr4,attr5,attr6")
    parser.add_argument("--select", help="selecton of attributes to be printed (default, [test], minimal, sr, all)")
    parser.add_argument("--sid", help="specify the sid to check for")
    parser.add_argument("--sort", help="specify the column name to sort by")
    parser.add_argument("--to", help="select 'to' - timepoint ('YYYY-M-D H:M:S')")
    parser.add_argument("--version", help="output version and exit", action="store_true")
    #parser.add_argument("--dumpFailures", help="print failed checks per loop",
    #                    action="store_true")
    args = parser.parse_args()
    if args.version:
        print(f"{TOOL_VERSION}")
        sys.exit(0)
    if args.cib:
        myCluster.config['cib_file_list'] = args.cib
    # args.from would create a namespace conflict so extracting 'from' using vars(args)
    if 'from' in vars(args) and vars(args)['from']:
        dt = dateutil_parser.parse(vars(args)['from'])
        myCluster.config['from'] = int(dt.timestamp())
    if args.format:
        myCluster.config['format'] = args.format
    if args.properties:
        myCluster.config['properties_file'] = args.properties
    if args.select:
        myCluster.config['select'] = args.select
    if args.sid:
        myCluster.config['sid'] = args.sid.lower()
    if args.sort:
        if args.sort[0] == '-':
            myCluster.config['sort-reverse'] = True
            myCluster.config['sort'] = args.sort[1:]
        elif args.sort[0] == '+':
            myCluster.config['sort-reverse'] = False
            myCluster.config['sort'] = args.sort[1:]
        else:
            myCluster.config['sort'] = args.sort
    if args.to:
        dt = dateutil_parser.parse(args.to)
        myCluster.config['to'] = int(dt.timestamp())
    if args.experimental_attributes:
        myCluster.config['show_attributes'] = args.experimental_attributes
        myCluster.config['select'] = 'cmdline'
        myCluster.set_selections()
    myCluster.read_properties()
    #
    # here the cib files iteration would begin
    #   - we need to read all given cib files
    #   - sort the found data dictionaries by cib-date
    #   - output all data dictionaries, filtered by from+to
    #
    for cib_file in myCluster.config['cib_file_list']:
        myHana    = HanaStatus(myCluster.config)
        myHana.xml_import(cib_file)
        multi_sid = False
        if myCluster.config['sid'] is None:
            myHana.get_sids()
            if len(myHana.sids) == 0:
                print("ERR: No SID found in cluster config")
                sys.exit(1)
            elif len(myHana.sids) > 1:
                print(f"WARN: Multiple SIDs found in cluster config: {str(myCluster.sids)} Please specify SID using --sid <SID>")
                multi_sid = False
                sys.exit(1)
            else:
                myHana.config['sid'] = myHana.sids[0].lower()
                myCluster.config['sid'] = myHana.sids[0].lower()
        myHana.fill_glob_dict()
        if 'cib-time' in myHana.glob_dict['global']:
            #print(f"dbg: test time filter")
            dt = dateutil_parser.parse(myHana.glob_dict['global']['cib-time'])
            cibtime = int(dt.timestamp())
            myHana.ts = cibtime
            if myCluster.config['from'] <= cibtime <= myCluster.config['to']:
                pass
            else:
                print(f"Filter cib-time {myHana.glob_dict['global']['cib-time']}")
                continue
        if len(myCluster.multi_status) == 0:
            myCluster.multi_status.insert(0, myHana)
        else:
            # search position where to insert the new hana_status
            pos = 0
            inserted = 0
            for hana_status in myCluster.multi_status:
                if myHana.ts < hana_status.ts:
                    myCluster.multi_status.insert(pos, myHana)
                    inserted = 1
                    break
                pos += 1
            if inserted == 0:
                myCluster.multi_status.insert(pos, myHana)  # insert at the end, if it is not inserted before
        myHana.fill_res_dict()
        myHana.fill_site_dict()
        myHana.fill_host_dict()

    for myHana in myCluster.multi_status:
        oformat = "table"
        if 'format' in myCluster.config:
            oformat = myCluster.config['format']
        if oformat == "table":
            index = myCluster.config['sort']
            index_type = 'str'
            index_reverse = myCluster.config['sort-reverse']
            if index is None:
                myHana.print_dic_as_table(myHana.glob_dict, "global", "Global")
                myHana.print_dic_as_table(myHana.res_dict, "resource", "Resource")
                myHana.print_dic_as_table(myHana.site_dict, "site", "Site")
                myHana.print_dic_as_table(myHana.host_dict, "host", "Host")
            else:
                myHana.print_dic_as_table_sort_by(myHana.glob_dict, index, index_type, index_reverse, "global",   "Global")
                myHana.print_dic_as_table_sort_by(myHana.res_dict, index, index_type, index_reverse, "resource", "Resource")
                myHana.print_dic_as_table_sort_by(myHana.site_dict, index, index_type, index_reverse, "site",     "Site")
                myHana.print_dic_as_table_sort_by(myHana.host_dict, index, index_type, index_reverse, "host",     "Host")
        elif oformat == "json":
            myHana.print_all_as_json()
        elif oformat in {"path", "script"}:
            cib_time=0
            if 'cib-time' in myHana.glob_dict["global"]:
                cib_time = myHana.glob_dict["global"]['cib-time']
            myHana.print_dic_as_path(myHana.glob_dict, "global", "Global", quote='"', ts=cib_time)
            myHana.print_dic_as_path(myHana.res_dict, "resource", "Resource", quote='"', ts=cib_time)
            myHana.print_dic_as_path(myHana.site_dict, "site", "Site", quote='"', ts=cib_time)
            myHana.print_dic_as_path(myHana.host_dict, "host", "Host", quote='"', ts=cib_time)
        elif oformat in {"tester"}:
            myHana.print_dic_as_path(myHana.glob_dict, "global", "Global", quote='"')
            myHana.print_dic_as_path(myHana.res_dict, "resource", "Resource", quote='"')
            myHana.print_dic_as_path(myHana.site_dict, "site", "Site", quote='"')
            myHana.print_dic_as_path(myHana.host_dict, "host", "Host", quote='"')
        elif oformat in {"cache"}:
            myHana.print_dic_as_csv(myHana.host_dict, "host", "Host", quote='', short=True)
        elif oformat in {"csv"}:
            myHana.print_dic_as_csv(myHana.glob_dict, "global", "Global", quote='')
            myHana.print_dic_as_csv(myHana.res_dict, "resource", "Resource", quote='')
            myHana.print_dic_as_csv(myHana.site_dict, "site", "Site", quote='')
            myHana.print_dic_as_csv(myHana.host_dict, "host", "Host", quote='')
