"""LEKO 下号（UIN）API 流程 RPA · step1 查询异常 · 企业微信告警（API 流程专用）。

与 source 流程 `rpa_leko_step1_search_error_sendmsg.py` 对应：
门户自动查询注册码时**检测到多家公司**（歧义，需要人工确认）时发企业微信群消息。

API 流程与 source 的差异：
- source 流程随后由 `rpa_leko_step1_search_error_update_reginfo.py` 直接回写
  source 库 `EPRRegInfo.PushTaxBureauStatus` + `Remarks`；
- API 流程改由 `rpa_leko_api_step1_search_error_update_task.py` 调服务端
  `/api/epr/leko-rpa/result`（status=failed）——服务端置 `rpa_status=3` 并按
  契约 §13 发送 SaaS 失败通知。两个脚本配合使用。

自包含约束：禁止 import 其它 rpa 脚本。
"""

import json

import requests

# 企业微信群消息发送配置（与 source 流程 rpa_leko_step1_search_error_sendmsg.py 同一 webhook）。
# ⚠️ 该 key 已进入 git 历史：建议在企业微信侧轮换后，改为从环境变量/配置注入，避免继续硬编码。
WECHAT_WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6b1d20eb-28ec-40b6-8ce5-ae91a11af1f4"


def send_wechat_group_message(
    business_serial_number: str,
    company_name: str,
    mentioned_mobile: str = None,
) -> bool:
    """发送「检测到多家公司」告警（文案与 source 流程保持一致）。

    :param business_serial_number: 任务里的 BusinessSerialNumber（业务流水号）
    :param company_name: 任务里的 NameEng（公司名）
    :param mentioned_mobile: 需要@的成员手机号（如业务顾问；API 流程可从任务
        bizParam 透传字段中取，缺省不 @）
    :return: 是否发送成功
    """
    message = f"{business_serial_number} {company_name} 自动查询注册码时检测到多家公司"

    payload = {
        "msgtype": "text",
        "text": {
            "content": message,
            "mentioned_mobile_list": [mentioned_mobile] if mentioned_mobile else []
        }
    }

    try:
        response = requests.post(
            WECHAT_WEBHOOK_URL,
            data=json.dumps(payload),
            headers={"Content-Type": "application/json"}
        )
        result = response.json()

        if result.get("errcode") == 0:
            print(f"消息发送成功: {message}")
            return True
        else:
            print(f"消息发送失败: {result}")
            return False

    except Exception as e:
        print(f"发送异常: {e}")
        return False
