"""
存客宝通讯录字段归一化 — 禁止空 nickname/display_name 占位

Hook/SQL 常返回 nickname 空、remark 有值；存客宝 MySQL diff 需要稳定展示字段。
"""

from __future__ import annotations

from typing import Any, Dict, List


def normalize_wechat_contact(raw: Dict[str, Any]) -> Dict[str, Any]:
    wxid = (
        raw.get("wxid")
        or raw.get("username")
        or raw.get("user_id")
        or ""
    ).strip()
    nickname = (raw.get("nickname") or "").strip()
    remark = (raw.get("remark") or raw.get("conRemark") or "").strip()
    alias = (raw.get("alias") or raw.get("wechat_id") or "").strip()
    display = nickname or remark or alias or wxid

    tags = raw.get("tags")
    if tags is None:
        tags = []
    elif isinstance(tags, str):
        tags = [t.strip() for t in tags.split(",") if t.strip()]

    sex_raw = raw.get("sex")
    if sex_raw in (0, "0", "unknown", None, ""):
        sex = "unknown"
    elif sex_raw in (1, "1", "male", "男"):
        sex = "male"
    elif sex_raw in (2, "2", "female", "女"):
        sex = "female"
    else:
        sex = str(sex_raw)

    return {
        "wxid": wxid,
        "user_id": wxid,
        "wechat_id": alias,
        "nickname": nickname,
        "display_name": display,
        "remark": remark,
        "alias": alias,
        "type": str(raw.get("type", "")),
        "sex": sex,
        "country": raw.get("country") or "",
        "province": raw.get("province") or "",
        "city": raw.get("city") or "",
        "signature": raw.get("signature") or "",
        "tags": tags,
        "has_avatar": bool(raw.get("has_avatar") or raw.get("imgFlag")),
        "phone": raw.get("phone") or raw.get("mobile") or "",
        "avatar": raw.get("avatar") or "",
    }


def normalize_wechat_contacts(contacts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    out: List[Dict[str, Any]] = []
    seen = set()
    for item in contacts or []:
        if not isinstance(item, dict):
            continue
        norm = normalize_wechat_contact(item)
        if not norm["wxid"] or norm["wxid"] in seen:
            continue
        seen.add(norm["wxid"])
        out.append(norm)
    return out
