#!/usr/bin/python3

import sys
import json

import zoneinfo

import logging
from logging.handlers import SysLogHandler

logger = logging.getLogger("update-sdf-timezone")
logger.setLevel(logging.INFO)

handler = SysLogHandler(address='/dev/log')

formatter = logging.Formatter('[%(levelname)-7s] | %(message)s')
handler.setFormatter(formatter)

logger.addHandler(handler)



def _find_and_update_param(config_list, target_key, new_options, count = 0):
    """
    Recursively searches a list of config items for a param with target_key
    and updates its "options".
    """
    for item in config_list:
        c_type = item.get("c_type")
        c_data = item.get("c_data", {})

        if c_type == "param" and c_data.get("key") == target_key:

            type_props = c_data.get("type_properties", {})

            type_props["options"] = new_options

            c_data["type_properties"] = type_props
            item["c_data"] = c_data
            count +=1
            return True

        elif c_type == "section":
            content = c_data.get("content")
            if content and isinstance(content, list):
                # _find_and_update_param(content, target_key, new_options)
                if _find_and_update_param(content, target_key, new_options):
                    return True

    # return True if count else False
    return False


def update_timezone_options():
    """
    Updates the timezone options in the SDF config file
    with the list from zoneinfo.
    """
    SDF_CONFIG_FILE_PATH = '/barix/apps/webui/common_lib/sdf/basic-settings-sdf-config.json'
    try:
        # 1. Get the list of timezones
        tz_list = sorted(list(zoneinfo.available_timezones()))

        # 2. Format them for the JSON structure
        new_options = [{"value": tz, "label": tz} for tz in tz_list]

        # 3. Read the existing JSON file
        try:
            with open(SDF_CONFIG_FILE_PATH, 'r', encoding='utf-8') as f:
                sdf_config = json.load(f)
        except FileNotFoundError:
            logger.error(f'SDF config file not found at: {SDF_CONFIG_FILE_PATH}')
            return -1
        except json.JSONDecodeError:
            logger.error(f'Failed to decode JSON from: {SDF_CONFIG_FILE_PATH}')
            return -1


        # 4. Find and update the timezone parameter
        config_data_list = sdf_config.get("config", [])
        was_updated = _find_and_update_param(config_data_list, "timezone", new_options)

        if not was_updated:
            logger.warning("Could not find 'timezone' parameter in SDF config.")
            return -1

        # 5. Write the updated data back to the file
        with open(SDF_CONFIG_FILE_PATH, 'w', encoding='utf-8') as f:
            # Use indent=2 to keep the file human-readable
            json.dump(sdf_config, f, indent=2)

        logger.info(f"Successfully updated timezone options. Added {len(new_options)} timezones.")
        return 0

    except Exception as e:
        logger.error(f'Error updating timezone options: {e}', exc_info=True)
        return -1
    

if __name__ == '__main__':
    sys.exit(update_timezone_options())
