

PROMOTE_KEYWORDS = ("type", "status", "lifecycle", "stage", "source")


def _is_picklist(f: dict) -> bool:
    t = str(f.get("type") or "").lower()
    return t in ("picklist", "multipicklist")


def _safe_values(f: dict) -> list[str]:
    out = []
    for v in f.get("picklistValues") or []:
        if v is None:
            continue
        try:
            if v.get("active", True):
                out.append(str(v.get("value") or "").strip())
        except Exception:
            continue
    # de-dup while preserving order
    seen = set()
    return [x for x in out if x and not (x in seen or seen.add(x))]


def discover_contact_catalog(desc: dict) -> dict:
    """Build a Contact field catalog for filters, promoting useful picklists.

    Returns:
      {
        "standard": ["AccountId", ...],
        "promoted": [{ name, label, values: [...] }],
        "all_picklists": [{ name, label }]
      }
    """
    fields = list(desc.get("fields", []) or [])
    picklists = [f for f in fields if _is_picklist(f)]

    promoted = []
    for f in picklists:
        name = (f.get("name") or "").strip()
        label = (f.get("label") or "").strip()
        low = f"{name} {label}".lower()
        if any(k in low for k in PROMOTE_KEYWORDS):
            promoted.append(
                {
                    "name": name,
                    "label": label or name,
                    "values": _safe_values(f),
                }
            )

    # ensure uniqueness by API name
    seen = set()
    promoted = [x for x in promoted if not (x["name"] in seen or seen.add(x["name"]))]

    return {
        "standard": ["AccountId", "OwnerId", "CreatedDate"],
        "promoted": promoted,
        "all_picklists": [
            {
                "name": (f.get("name") or ""),
                "label": (f.get("label") or f.get("name") or ""),
            }
            for f in picklists
        ],
    }
