"""RedPepper Manager configuration"""

import glob
import secrets

import yaml

DEFAULT_CONFIG_FILE = "/etc/redpepper-agent/agent.yml"

defaults = {
    "agent_id": None,
    "agent_secret": "",
    "data_request_timeout": 5,
    "hello_timeout": 3,
    "include": ["/etc/redpepper-agent/agent.d/*.yml"],
    "manager_host": "localhost",
    "manager_port": 7051,
    "ping_interval": 30,
    "ping_timeout": 5,
    "operation_modules_cache_dir": "/var/lib/redpepper-agent/operations",
    "tls_ca_file": None,
    "tls_ca_path": None,
    "tls_ca_data": None,
    "tls_cert_file": "/etc/redpepper-agent/agent-cert.pem",
    "tls_check_hostname": True,
    "tls_key_file": "/etc/redpepper-agent/agent-key.pem",
    "tls_key_password": None,
    "tls_verify_mode": "required",
}


def load_agent_config(config_file=None):
    if config_file is None:
        config_file = DEFAULT_CONFIG_FILE
    conf = defaults.copy()
    try:
        with open(config_file, "r") as stream:
            yml = yaml.safe_load(stream)
    except FileNotFoundError:
        yml = None
    if yml:
        conf.update(yml)
    process_includes(conf, [config_file])
    if not conf["agent_id"]:
        conf["agent_id"] = "autogenerated_" + secrets.token_hex(8)
    return conf


def process_includes(conf, included_files):
    if "include" not in conf:
        return
    for pattern in conf.pop("include"):
        for filename in glob.glob(pattern):
            if filename in included_files:
                continue
            included_files.append(filename)
            with open(filename, "r") as stream:
                included_yml = yaml.safe_load(stream)
            if included_yml:
                if not isinstance(included_yml, dict):
                    raise ValueError(f"The YAML file {filename} is not a mapping")
                conf.update(included_yml)
                process_includes(included_yml, included_files)
