"""BooruGacha Combine Bans — merge multiple ban lists into one."""


class _FlexibleInputs(dict):
    def __contains__(self, key):
        return True

    def __getitem__(self, key):
        if key in self.keys():
            return super().__getitem__(key)
        return ("BANLIST",)


class BooruGachaCombineBans:
    """Merges multiple ``BANLIST`` inputs into a single unified ban set."""

    DESCRIPTION = (
        "Combines multiple ban lists into one. "
        "Use the Add Input button to add more connections."
    )

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {},
            "optional": _FlexibleInputs(),
        }

    RETURN_TYPES = ("BANLIST", "STRING")
    RETURN_NAMES = ("ban_list", "debug_info")
    OUTPUT_TOOLTIPS = (
        "Merged ban set",
        "Per-input counts",
    )
    FUNCTION = "combine"
    CATEGORY = "BooruGacha"

    def combine(self, **kwargs):
        merged: set[str] = set()
        debug_lines: list[str] = []

        for key in sorted(kwargs):
            value = kwargs[key]
            if isinstance(value, set):
                before = len(merged)
                merged.update(value)
                added = len(merged) - before
                debug_lines.append(f"{key}: {len(value)} tags ({added} new)")

        debug_lines.insert(0, f"Total: {len(merged)} banned tags")
        return (merged, "\n".join(debug_lines))
