from __future__ import annotations

import json
from typing import Any, Dict, Iterable


def parse_kv_items(items: Iterable[str], *, lowercase_keys: bool = True) -> Dict[str, Any]:
    """
    Parse items like key=value into a dict.

    - Preserves values containing '=' (e.g., base64 '...==') by splitting only once.
    - Attempts json.loads on RHS; falls back to string.
    """
    out: Dict[str, Any] = {}
    for item in items:
        if "=" not in item:
            continue

        k, v = item.split("=", 1)   # CLAVE
        k = k.strip()
        v = v.strip()
        if not k:
            continue

        if lowercase_keys:
            k = k.lower()

        try:
            parsed = json.loads(v)
        except Exception:
            parsed = v

        out[k] = parsed
    return out
