import json
import re
import os
import sys
import time
import shutil
import subprocess
import yaml

support_dir = "/var/log/netq-agent/obj-model/spice_support"
config_file = ""
"/etc/netq/config.d/spice/netq-spice-config.yml"

def expand_range(path_regex):
    if "*" in path_regex:
        path_regex = path_regex.replace("*", "")

    matches = re.findall(r'\[(\d+)-(\d+)\]', path_regex)
    _expanded_xpaths = [path_regex]
    if matches:
        for match in matches:
            start = int(match[0])
            end = int(match[1])
            new_expanded_xpaths = []
            # Expand the current range in each existing xpath
            for entry in _expanded_xpaths:
                new_expanded_xpaths.extend([entry.replace(f"[{start}-{end}]", f"{i}") for i in range(start, end+1)])

            _expanded_xpaths = new_expanded_xpaths
    return _expanded_xpaths


try:
    asic_model_cmd = "nv show platform -o json"
    result = subprocess.run(asic_model_cmd.split(), capture_output=True, text=True)
    if result.returncode == 0:
        try:
            json_output = json.loads(result.stdout)
            if json_output["asic-model"] == "Spectrum-4":
                config_file = "/etc/netq/config.d/spice/netq-spice-config-spc4.yml"
            elif json_output["asic-model"] in ("Spectrum-3", "Spectrum-2"):
                config_file = "/etc/netq/config.d/spice/netq-spice-config.yml"
            else:
                print(f"Unsupported platform for Spice support")
                sys.exit()

        except json.JSONDecodeError as e:
            print("Error decoding JSON:", e)
    else:
        print("Command failed with return code:", result.returncode)
except Exception as ex:
    print("Command - ", asic_model_cmd, ": Failed to read ASIC model:", ex)
    pass


if not os.path.exists(config_file):
    print(f"File {config_file} not found")
    sys.exit()

timestamp = int(time.time())
support_dir = support_dir + "/" + str(timestamp)
if not os.path.exists(support_dir):
    os.makedirs(support_dir)

with open(config_file, 'r') as f:
    config_dict = yaml.safe_load(f)
    for section, section_data in config_dict.items():
        # Process local group settings
        if section == 'spice':
            spice_section = section_data

            whitelists = spice_section.get("whitelists", [])
            for whitelist in whitelists:
                period = int(whitelist.get('period'))
                read_fails = int(whitelist.get('read-fails'))
                timeout = int(whitelist.get('timeout'))
                scope = str(whitelist.get('scope'))
                if "global" in scope:
                    is_global = True
                else:
                    is_global = False

                models = whitelist.get("groups", [])
                for model in models:
                    xpaths = model.get("xpaths", [])
                    for xpath in xpaths:
                        xpath_value = xpath.get('xpath')
                        expanded_xpaths = expand_range(xpath_value)
                        for expanded_xpath in expanded_xpaths:
                            if not os.path.exists(expanded_xpath):
                                continue

                            dest_dir = support_dir + "/" + os.path.dirname(expanded_xpath)
                            if not os.path.exists(dest_dir):
                                os.makedirs(dest_dir)

                            shutil.copy(expanded_xpath, dest_dir)
