"""微信 Open Platform OAuth 扫码登录（第一版已注释，待后续启用）"""

# import hashlib
# import logging
# from urllib.parse import urlencode
#
# import httpx
#
# from app.config import settings
#
# logger = logging.getLogger(__name__)
#
# _APP_ID = settings.WECHAT_OAUTH_APP_ID
# _APP_SECRET = settings.WECHAT_OAUTH_APP_SECRET
#
# WECHAT_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token"
# WECHAT_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo"
# WECHAT_AUTHORIZE_URL = "https://open.weixin.qq.com/connect/qrconnect"
#
#
# def is_dev_mode() -> bool:
#     return not _APP_ID or not _APP_SECRET
#
#
# def get_authorize_url(state: str, redirect_uri: str = "") -> str:
#     """构造微信扫码授权 URL"""
#     if not redirect_uri:
#         redirect_uri = f"{settings.PUBLIC_BASE_URL}/api/v1/auth/wechat/callback"
#     params = urlencode({
#         "appid": _APP_ID if not is_dev_mode() else "mock_appid",
#         "redirect_uri": redirect_uri,
#         "response_type": "code",
#         "scope": "snsapi_login",
#         "state": state,
#     })
#     return f"{WECHAT_AUTHORIZE_URL}?{params}#wechat_redirect"
#
#
# async def exchange_code_for_token(code: str) -> dict:
#     """用授权 code 换取 access_token + openid"""
#     if is_dev_mode():
#         # 用 code 做种子生成确定性 openid，方便测试
#         digest = hashlib.md5(code.encode()).hexdigest()
#         return {
#             "access_token": f"mock_access_{digest[:16]}",
#             "expires_in": 7200,
#             "refresh_token": f"mock_refresh_{digest[:16]}",
#             "openid": f"mock_openid_{digest[:16]}",
#             "scope": "snsapi_login",
#         }
#
#     async with httpx.AsyncClient() as client:
#         resp = await client.get(WECHAT_ACCESS_TOKEN_URL, params={
#             "appid": _APP_ID,
#             "secret": _APP_SECRET,
#             "code": code,
#             "grant_type": "authorization_code",
#         })
#     data = resp.json()
#     if "errcode" in data:
#         logger.error("WeChat token exchange failed: %s", data)
#         raise ValueError(f"WeChat OAuth error: {data.get('errmsg', 'unknown')}")
#     return data
#
#
# async def get_user_info(access_token: str, openid: str) -> dict:
#     """获取微信用户基本信息（昵称、头像等）"""
#     if is_dev_mode():
#         suffix = openid[-8:] if len(openid) >= 8 else openid
#         return {
#             "openid": openid,
#             "nickname": f"微信用户_{suffix}",
#             "sex": 0,
#             "province": "",
#             "city": "",
#             "country": "",
#             "headimgurl": "",
#             "unionid": "",
#         }
#
#     async with httpx.AsyncClient() as client:
#         resp = await client.get(WECHAT_USERINFO_URL, params={
#             "access_token": access_token,
#             "openid": openid,
#         })
#     data = resp.json()
#     if "errcode" in data:
#         logger.error("WeChat userinfo failed: %s", data)
#         raise ValueError(f"WeChat userinfo error: {data.get('errmsg', 'unknown')}")
#     return data
#
#
# def make_synthetic_email(openid: str) -> str:
#     """为微信用户生成唯一合成邮箱"""
#     digest = hashlib.md5(openid.encode()).hexdigest()[:16]
#     return f"wc_{digest}@wechat.user"
