# -*- coding: utf-8 -*-
"""
企业微信自建应用回调服务
接收@机器人消息，查询巨量本地推数据并回复。
"""
import base64
import hashlib
import json
import os
import re
import struct
import subprocess
import sys
import threading
import time
import xml.etree.ElementTree as ET
from io import BytesIO

import openpyxl
import requests
from Crypto.Cipher import AES
from flask import Flask, request

# ============ 配置 ============
# 企业微信自建应用凭证（回调加解密用，不常变，保留在此）
CORP_ID = "ww61652e0949f8a473"
AGENT_ID = 1000008
SECRET = "EnvhhyO3_10XoONXr8RmQ2eZn9z_w_hz81KVH_RdCds"
TOKEN = "oWS8uNdJtAdrbJhbKn0ceME5Iu"
ENCODING_AES_KEY = "xlbj6tK6LEUDaSsGktxsY5TajM1ywrAGCfQEOjvtrjt"

# 数据API token 与 群webhook 统一从 config.json 读取，避免凭证三处重复
APP_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(APP_DIR, "config.json")
XLSX_PATH = os.path.join(APP_DIR, "账户简称.xlsx")


def _load_cfg():
    try:
        with open(CONFIG_PATH, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {}


_CFG = _load_cfg()
WECHAT_WEBHOOK = _CFG.get("wechat_webhook", "")
OCEANENGINE_TOKEN = _CFG.get("oceanengine_access_token", "")


def load_accounts():
    """账户列表统一从 账户简称.xlsx 读取；缺失时回退 config.json 的 accounts。"""
    if os.path.exists(XLSX_PATH):
        try:
            wb = openpyxl.load_workbook(XLSX_PATH, data_only=True)
            ws = wb.active
            accs = []
            for row in ws.iter_rows(min_row=2, values_only=True):
                cells = list(row) + [None, None, None]
                id_raw, short = cells[1], cells[2]
                if id_raw is None:
                    continue
                aid = str(id_raw).replace("ID：", "").replace("ID:", "").replace("：", "").strip()
                name = (str(short).strip() if short is not None else "") or \
                       (str(cells[0]).strip() if cells[0] is not None else "")
                if aid:
                    accs.append((aid, name))
            if accs:
                return accs
        except Exception:
            pass
    return [(a["id"], a["name"]) for a in _CFG.get("accounts", [])]


ACCOUNTS = load_accounts()

app = Flask(__name__)


# ============ 企业微信加解密 ============
class WXBizMsgCrypt:
    def __init__(self, token, encoding_aes_key, corp_id):
        self.token = token
        self.key = base64.b64decode(encoding_aes_key + "=")
        self.corp_id = corp_id

    def _sign(self, timestamp, nonce, echo_str=None):
        arr = sorted([self.token, timestamp, nonce] + ([echo_str] if echo_str else []))
        return hashlib.sha1("".join(arr).encode()).hexdigest()

    def verify_url(self, msg_signature, timestamp, nonce, echo_str):
        sign = self._sign(timestamp, nonce, echo_str)
        if sign != msg_signature:
            return None
        return self._decrypt(echo_str)

    def decrypt_msg(self, msg_signature, timestamp, nonce, post_body):
        xml_tree = ET.fromstring(post_body)
        encrypt = xml_tree.find("Encrypt").text
        sign = self._sign(timestamp, nonce, encrypt)
        if sign != msg_signature:
            return None
        return self._decrypt(encrypt)

    def _decrypt(self, text):
        cipher = AES.new(self.key, AES.MODE_CBC, self.key[:16])
        plain = cipher.decrypt(base64.b64decode(text))
        pad = plain[-1]
        plain = plain[:-pad]
        content = plain[16:20]
        msg_len = struct.unpack("!I", content)[0]
        msg = plain[20:20 + msg_len].decode("utf-8")
        receive_id = plain[20 + msg_len:].decode("utf-8")
        return msg, receive_id

    def encrypt_msg(self, reply_msg, nonce, timestamp=None):
        if timestamp is None:
            timestamp = str(int(time.time()))
        msg = reply_msg.encode("utf-8")
        random16 = hashlib.md5(str(time.time()).encode()).digest()[:16]
        buf = random16 + struct.pack("!I", len(msg)) + msg + self.corp_id.encode("utf-8")
        pad = 32 - (len(buf) % 32)
        buf += bytes([pad] * pad)
        cipher = AES.new(self.key, AES.MODE_CBC, self.key[:16])
        encrypted = base64.b64encode(cipher.encrypt(buf)).decode()
        sign = self._sign(timestamp, nonce, encrypted)
        return f"""<xml>
<Encrypt><![CDATA[{encrypted}]]></Encrypt>
<MsgSignature><![CDATA[{sign}]]></MsgSignature>
<TimeStamp>{timestamp}</TimeStamp>
<Nonce><![CDATA[{nonce}]]></Nonce>
</xml>"""


# ============ 巨量引擎数据查询 ============
def fetch_oceanengine_data():
    from datetime import datetime
    today = datetime.now().strftime("%Y-%m-%d")
    metrics = '["stat_cost","attribution_convert_cnt","attribution_convert_cost","attribution_message_action_cnt","attribution_clue_confirm","attribution_clue_confirm_cost"]'
    headers = {"Access-Token": OCEANENGINE_TOKEN}
    results = []
    for aid, name in ACCOUNTS:
        try:
            url = f"https://api.oceanengine.com/open_api/v3.0/local/report/account/get/?local_account_id={aid}&start_date={today}&end_date={today}&metrics={metrics}&page=1&page_size=10"
            r = requests.get(url, headers=headers, timeout=15).json()
            if r.get("code") == 0:
                rows = (r.get("data") or {}).get("data_list") or []
                if rows:
                    d = rows[0]
                    cost = d.get("stat_cost", 0) or 0
                    if cost > 0:
                        results.append({
                            "name": name,
                            "cost": cost,
                            "conv": d.get("attribution_convert_cnt", 0) or 0,
                            "msg": d.get("attribution_message_action_cnt", 0) or 0,
                            "intent": d.get("attribution_clue_confirm", 0) or 0,
                            "intent_cost": d.get("attribution_clue_confirm_cost", 0) or 0,
                        })
        except Exception:
            pass
        time.sleep(0.3)
    return results


def build_reply_text():
    data = fetch_oceanengine_data()
    now = time.strftime("%H:%M")
    lines = [f"📊 巨量本地推实时数据 ({now})"]
    if not data:
        lines.append("今日暂无消耗")
        return "\n".join(lines)

    total_cost = sum(d["cost"] for d in data)
    total_conv = sum(d["conv"] for d in data)
    total_msg = sum(d["msg"] for d in data)
    total_intent = sum(d["intent"] for d in data)
    lines.append(f"合计：消耗¥{total_cost:.0f} 转化{total_conv} 私信{total_msg} 意向{total_intent}")
    lines.append("")
    for d in data:
        line = f"{d['name']}：消耗¥{d['cost']:.0f} 转化{d['conv']} 私信{d['msg']} 意向{d['intent']}"
        if d["intent"] > 0:
            line += f" 意向成本¥{d['intent_cost']:.0f}"
        lines.append(line)
    return "\n".join(lines)


# ============ 实时查询：查数据并推送到企业群 ============
def query_via_local():
    """调用同目录的 juliang_monitor.exe --query（找不到则用 monitor.py --query），
    解析预警文字并读取生成的 query_table.png，返回 (alert_text, img_b64, img_md5)。"""
    cwd = APP_DIR
    exe = os.path.join(cwd, "juliang_monitor.exe")
    if os.path.exists(exe):
        cmd = [exe, "--query"]
    else:
        py = os.path.join(cwd, "monitor.py")
        cmd = [sys.executable, py, "--query"] if os.path.exists(py) else None
    if not cmd:
        return None
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, cwd=cwd, timeout=180)
    except Exception as e:
        print("query subprocess error:", e)
        return None
    out = r.stdout or ""
    m = re.search(r"===ALERT_TEXT_START===(.*?)===ALERT_TEXT_END===", out, re.S)
    alert = m.group(1).strip() if m else ""
    png = os.path.join(cwd, "query_table.png")
    if not os.path.exists(png):
        return None
    data = open(png, "rb").read()
    img_b64 = base64.b64encode(data).decode("utf-8")
    img_md5 = hashlib.md5(data).hexdigest()
    return alert, img_b64, img_md5


def push_text_to_group(text):
    """把纯文字消息发到企业微信群（webhook），返回是否成功。"""
    if not WECHAT_WEBHOOK:
        print("WECHAT_WEBHOOK 为空，跳过群推送")
        return False
    try:
        requests.post(WECHAT_WEBHOOK,
                      json={"msgtype": "text", "text": {"content": text}},
                      timeout=30)
        return True
    except Exception as e:
        print("群推送文字失败:", e)
        return False


def push_to_group(text, img_b64=None, img_md5=None):
    """把预警文字 + 表格图片发到企业微信群（webhook）。"""
    push_text_to_group(text)
    if img_b64 and img_md5:
        try:
            requests.post(WECHAT_WEBHOOK,
                          json={"msgtype": "image", "image": {"base64": img_b64, "md5": img_md5}},
                          timeout=30)
        except Exception as e:
            print("群推送图片失败:", e)


def _async_query_and_push():
    q = query_via_local()
    if q:
        alert, img_b64, img_md5 = q
        push_to_group(alert, img_b64, img_md5)
    else:
        print("实时查询失败，未推送到群")


# ============ 企业微信应用主动发消息（异步结果回传） ============
_WX_TOKEN = None
_WX_TOKEN_EXPIRE = 0


def get_wechat_token():
    global _WX_TOKEN, _WX_TOKEN_EXPIRE
    now = time.time()
    if _WX_TOKEN and now < _WX_TOKEN_EXPIRE:
        return _WX_TOKEN
    try:
        r = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken",
                         params={"corpid": CORP_ID, "corpsecret": SECRET}, timeout=10).json()
        if r.get("errcode") == 0:
            _WX_TOKEN = r["access_token"]
            _WX_TOKEN_EXPIRE = now + r.get("expires_in", 7200) - 300
            return _WX_TOKEN
    except Exception as e:
        print("获取企业微信 token 异常:", e)
    return None


def send_app_message(touser, content):
    tk = get_wechat_token()
    if not tk:
        print("获取企业微信 token 失败，无法主动回传消息")
        return False
    try:
        r = requests.post("https://qyapi.weixin.qq.com/cgi-bin/message/send",
                          params={"access_token": tk},
                          json={"touser": touser, "msgtype": "text", "agentid": AGENT_ID,
                                "text": {"content": content}},
                          timeout=15).json()
        return r.get("errcode") == 0
    except Exception as e:
        print("主动发消息失败:", e)
        return False


# ============ 回调路由 ============
crypt = None


@app.route("/wechat/callback", methods=["GET", "POST"])
def callback():
    global crypt
    if crypt is None:
        crypt = WXBizMsgCrypt(TOKEN, ENCODING_AES_KEY, CORP_ID)

    msg_signature = request.args.get("msg_signature", "")
    timestamp = request.args.get("timestamp", "")
    nonce = request.args.get("nonce", "")

    if request.method == "GET":
        echo_str = request.args.get("echostr", "")
        result = crypt.verify_url(msg_signature, timestamp, nonce, echo_str)
        if result:
            return result[0]
        return "verify failed", 403

    # POST: 接收消息
    body = request.data
    result = crypt.decrypt_msg(msg_signature, timestamp, nonce, body)
    if not result:
        return "decrypt failed", 403

    msg, _ = result
    xml_tree = ET.fromstring(msg)
    msg_type = xml_tree.find("MsgType").text
    from_user = xml_tree.find("FromUserName").text

    if msg_type == "text":
        content = xml_tree.find("Content").text.strip()

        if any(k in content for k in ["数据", "报表", "盯盘", "消耗", "查", "行情", "今日"]):
            # 后台查询并推送到企业群；被动先回一句提示，避免超过企业微信5秒回调超时
            t = threading.Thread(target=_async_query_and_push, daemon=True)
            t.start()
            reply = "已收到，正在为您查询，今日盯盘数据将发至企业群，请稍候查收 👇"
        else:
            reply = ("指令帮助：\n"
                     "· 发「数据」查今日盯盘（推企业群）")
    else:
        reply = "发送「数据」获取今日投放数据"

    return crypt.encrypt_msg(reply, nonce, timestamp)


if __name__ == "__main__":
    print("企业微信回调服务启动中...")
    print("回调地址: http://0.0.0.0:5000/wechat/callback")
    app.run(host="0.0.0.0", port=5000, debug=False)
