"""Merge config.yaml over default-config.yaml into merged-config.yaml."""

import copy
import grp
import os
import pwd
import sys

import yaml

DEFAULT_CONFIG = "/etc/cyber-frame-connector/default-config.yaml"
OVERRIDE_CONFIG = "/etc/cyber-frame-connector/config.yaml"
MERGED_CONFIG = "/etc/cyber-frame-connector/merged-config.yaml"
STAGING_CONFIG = "/etc/cyber-frame-connector/.merged-config.yaml.new"
SERVICE_USER = "vstoradmin"
SERVICE_GROUP = "root"


def deep_merge(base: dict, override: dict) -> dict:
    result = copy.deepcopy(base)
    for key, value in override.items():
        if (
            key in result
            and isinstance(result[key], dict)
            and isinstance(value, dict)
        ):
            result[key] = deep_merge(result[key], value)
        else:
            result[key] = copy.deepcopy(value)
    return result


def main() -> int:
    for path in (DEFAULT_CONFIG, OVERRIDE_CONFIG):
        if not os.path.isfile(path):
            print(f"Missing required config file: {path}", file=sys.stderr)
            return 1

    with open(DEFAULT_CONFIG, encoding="utf-8") as fh:
        base = yaml.safe_load(fh) or {}
    with open(OVERRIDE_CONFIG, encoding="utf-8") as fh:
        override = yaml.safe_load(fh) or {}

    if not isinstance(base, dict) or not isinstance(override, dict):
        print("Config files must contain YAML mappings at the top level", file=sys.stderr)
        return 1

    merged = deep_merge(base, override)

    fd = os.open(STAGING_CONFIG, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as fh:
        yaml.safe_dump(
            merged,
            fh,
            default_flow_style=False,
            sort_keys=False,
        )

    uid = pwd.getpwnam(SERVICE_USER).pw_uid
    gid = grp.getgrnam(SERVICE_GROUP).gr_gid
    os.chown(STAGING_CONFIG, uid, gid)
    os.replace(STAGING_CONFIG, MERGED_CONFIG)
    return 0


if __name__ == "__main__":
    sys.exit(main())
