import re
import os
import sys
import time
import shutil
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

nvue_client = None
try:
    # Use NVUE API client to get platform information
    from netq_agent.cmd.nvue_api_client import create_nvue_client
    nvue_client = create_nvue_client()
    json_output = nvue_client.get_platform_hardware()

    if json_output:
        asic_model = json_output.get("asic-model")
        if asic_model == "Spectrum-4":
            config_file = "/etc/netq/config.d/spice/netq-spice-config-spc4.yml"
        elif 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: {asic_model}")
            sys.exit()
    else:
        print("Failed to get platform information from NVUE API")
except Exception as ex:
    print("NVUE API platform command: Failed to read ASIC model:", ex)
    pass
finally:
    # Clean up NVUE client connection
    if nvue_client:
        nvue_client.close()


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)
