"""Merge feature-pack config across codegen runs.

``p2hs/feature-packs.json`` is often omitted or re-declared with ``config: {}``
on later prompts. Reinstall must not wipe owner-supplied keys such as
``notify_to_email``.
"""
from __future__ import annotations

from typing import Any


def merge_pack_config(previous: dict[str, Any] | None, incoming: dict[str, Any] | None) -> dict[str, Any]:
    """Overlay declared keys onto the last installed config.

    Empty incoming values are omitted so a force-reinstall with ``config={}``
    keeps what was already stored.
    """
    merged = dict(previous or {})
    for key, value in dict(incoming or {}).items():
        if value is None or value == "":
            continue
        if value == {} or value == []:
            continue
        merged[key] = value
    return merged


def union_notify_emails(*groups: str) -> str:
    seen: list[str] = []
    found: set[str] = set()
    for group in groups:
        for part in str(group or "").split(","):
            email = part.strip().lower()
            if not email or email in found:
                continue
            found.add(email)
            seen.append(email)
    return ", ".join(seen)
