# -*- coding: utf-8 -*-
"""
巨量本地推整点盯盘脚本
每整点拉取各账户消耗、转化、私信咨询、确认意向等数据，推送到企业微信群。
确认意向成本超过阈值的账户会重点标红提醒。
"""
import json
import os
import sys
import time
import msvcrt
from datetime import datetime
from urllib.parse import urlencode

import requests

from PIL import Image, ImageDraw, ImageFont

# 修复Windows控制台编码问题
if sys.platform == 'win32':
    sys.stdout.reconfigure(encoding='utf-8', errors='replace')

if getattr(sys, 'frozen', False):
    # 打包成exe后，用exe所在目录
    APP_DIR = os.path.dirname(sys.executable)
else:
    # 开发模式，用脚本所在目录
    APP_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(APP_DIR, "config.json")
REPORT_API = "https://api.oceanengine.com/open_api/v3.0/local/report/account/get/"

METRICS = [
    "stat_cost",                          # 消耗(元)
    "attribution_convert_cnt",            # 转化数(计费时间)
    "attribution_convert_cost",           # 转化成本(元)(计费时间)
    "attribution_message_action_cnt",     # 私信咨询数(计费时间)
    "attribution_clue_confirm",           # 确认意向数(计费时间)
    "attribution_clue_confirm_cost",      # 确认意向成本(元)(计费时间)
]


def load_config():
    with open(CONFIG_PATH, "r", encoding="utf-8") as f:
        return json.load(f)


def load_accounts():
    """从Excel读取账户列表，找不到就从config.json读"""
    xlsx_path = os.path.join(APP_DIR, "账户简称.xlsx")
    accounts = []
    if os.path.exists(xlsx_path):
        try:
            import openpyxl
            wb = openpyxl.load_workbook(xlsx_path, read_only=True)
            ws = wb.active
            for i, row in enumerate(ws.iter_rows(min_row=2, values_only=True)):
                if not row or not row[1]:
                    continue
                # 第二列是"ID：1867687774651456"格式，提取数字
                id_str = str(row[1]).replace("ID：", "").replace("ID:", "").strip()
                name = str(row[2]).strip() if row[2] else f"账户{i+1}"
                try:
                    acc_id = int(id_str)
                    accounts.append({"id": acc_id, "name": name})
                except ValueError:
                    continue
            wb.close()
        except Exception as e:
            print(f"读取Excel失败: {e}，回退到config.json")
            accounts = []
    if not accounts:
        # 回退到config.json
        config = load_config()
        accounts = config.get("accounts", [])
    # 写成accounts.json给PHP用
    try:
        with open(os.path.join(APP_DIR, "accounts.json"), "w", encoding="utf-8") as f:
            json.dump(accounts, f, ensure_ascii=False, indent=2)
    except Exception:
        pass
    return accounts


def fetch_account_report(access_token, local_account_id, start_date, end_date):
    """调用本地推账户维度报表 API，返回汇总数据 dict。"""
    params = {
        "local_account_id": local_account_id,
        "start_date": start_date,
        "end_date": end_date,
        "metrics": json.dumps(METRICS),
        "page": 1,
        "page_size": 10,
    }
    url = REPORT_API + "?" + urlencode(params)
    headers = {"Access-Token": access_token}
    try:
        resp = requests.get(url, headers=headers, timeout=30)
        data = resp.json()
    except Exception as e:
        return {"error": f"请求异常: {e}"}

    if data.get("code") != 0:
        return {"error": f"API错误 code={data.get('code')} msg={data.get('message')}"}

    rows = (data.get("data") or {}).get("data_list") or []
    if not rows:
        return {
            "stat_cost": 0,
            "attribution_convert_cnt": 0,
            "attribution_convert_cost": 0,
            "attribution_message_action_cnt": 0,
            "attribution_clue_confirm": 0,
            "attribution_clue_confirm_cost": 0,
        }
    # 汇总（一般一天就一行）
    row = rows[0]
    return {k: row.get(k, 0) for k in METRICS}


def fetch_budgets(access_token, account_ids):
    """批量获取账户日预算。"""
    url = "https://api.oceanengine.com/open_api/v3.0/local/advertiser/budget/get/"
    # 转成整数数组，API要求数字类型
    ids_int = [int(x) for x in account_ids]
    params = {"local_account_id": json.dumps(ids_int)}
    headers = {"Access-Token": access_token}
    try:
        resp = requests.get(url, params=params, headers=headers, timeout=15)
        data = resp.json()
    except Exception:
        return {}
    if data.get("code") != 0:
        return {}
    budgets = {}
    for item in (data.get("data") or {}).get("list") or []:
        budgets[str(item["advertiser_id"])] = {
            "budget": item.get("budget", 0),
            "budget_mode": item.get("budget_mode", ""),
        }
    return budgets


def build_message(results, threshold, now_str, budgets=None):
    """构建企业微信纯文本消息——每行一个账户，手机端易读。"""
    if budgets is None:
        budgets = {}
    lines = []
    lines.append(f"📊 巨量本地推盯盘 {now_str}")

    # 只统计有消耗的账户
    active = []
    for r in results:
        d = r["data"]
        if "error" in d:
            continue
        if (d.get("stat_cost", 0) or 0) > 0:
            active.append(r)

    # 汇总（只算有消耗的）
    total_cost = sum(r["data"].get("stat_cost", 0) for r in active)
    total_conv = sum(r["data"].get("attribution_convert_cnt", 0) for r in active)
    total_msg = sum(r["data"].get("attribution_message_action_cnt", 0) for r in active)
    total_intent = sum(r["data"].get("attribution_clue_confirm", 0) for r in active)

    lines.append(f"💰 合计：消耗¥{total_cost:.0f} | 转化{total_conv} | 私信{total_msg} | 意向{total_intent}")
    if total_intent > 0:
        total_intent_cost = total_cost / total_intent
        lines.append(f"   整体意向成本：¥{total_intent_cost:.0f}")
    lines.append("")

    # 超标预警
    over_threshold = []
    no_conv = []
    no_intent = []
    good_perf = []  # 效果好可加预算
    for r in active:
        d = r["data"]
        cost = d.get("stat_cost", 0) or 0
        conv = d.get("attribution_convert_cnt", 0) or 0
        intent = d.get("attribution_clue_confirm", 0) or 0
        intent_cost = d.get("attribution_clue_confirm_cost", 0) or 0

        if intent > 0 and intent_cost > threshold:
            over_threshold.append((r["name"], intent_cost, intent))
        if cost > 200 and conv == 0:
            no_conv.append((r["name"], cost))
        if cost > 300 and intent == 0:
            no_intent.append((r["name"], cost))
        if intent > 0 and 0 < intent_cost < threshold:
            good_perf.append((r["name"], intent_cost, cost, r["id"]))

    if over_threshold:
        lines.append(f"🔴 意向成本超¥{threshold}预警：")
        for name, cost, cnt in over_threshold:
            lines.append(f"  {name}：¥{cost:.0f}（{cnt}个意向）")
        lines.append("")

    if no_conv:
        lines.append("⚠️ 消耗超¥200无转化：")
        for name, cost in no_conv:
            lines.append(f"  {name}：消耗¥{cost:.0f} 转化0")
        lines.append("")

    if no_intent:
        lines.append("⚠️ 消耗超¥300无意向：")
        for name, cost in no_intent:
            lines.append(f"  {name}：消耗¥{cost:.0f} 意向0")
        lines.append("")

    if good_perf:
        lines.append("🟢 效果好可加预算（意向成本<¥300）：")
        for item in good_perf:
            gname, icost, cost, acc_id = item
            binfo = budgets.get(acc_id, {})
            budget = binfo.get("budget", 0)
            bmode = binfo.get("budget_mode", "")
            if bmode == "BUDGET_MODE_INFINITE" or budget == 0:
                lines.append(f"  {gname}：意向成本¥{icost:.0f} 已消耗¥{cost:.0f}（预算不限）")
            else:
                remain = budget - cost
                warn = " ⚠️剩余<¥1000" if remain < 1000 else ""
                lines.append(f"  {gname}：意向成本¥{icost:.0f} 已消耗¥{cost:.0f}/预算¥{budget:.0f}{warn}")
        lines.append("")

    # 有消耗的账户明细
    if not active:
        lines.append("今日暂无消耗账户")
    else:
        lines.append("--- 有消耗账户 ---")
        for r in active:
            name = r["name"]
            d = r["data"]
            cost = d.get("stat_cost", 0) or 0
            conv = d.get("attribution_convert_cnt", 0) or 0
            conv_cost = d.get("attribution_convert_cost", 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

            line = f"{name}：消耗¥{cost:.0f} 转化{conv} 私信{msg} 意向{intent}"
            if intent > 0:
                line += f" 意向成本¥{intent_cost:.0f}"
            lines.append(line)

    return "\n".join(lines)


def generate_table_image(results, threshold, now_str, budgets=None):
    """生成盯盘表格图片——只放有消耗账户明细+合计。"""
    if budgets is None:
        budgets = {}

    # 只统计有消耗的账户
    active = []
    for r in results:
        d = r["data"]
        if "error" in d:
            continue
        if (d.get("stat_cost", 0) or 0) > 0:
            active.append(r)

    # 按消耗从高到低排序
    active.sort(key=lambda x: x["data"].get("stat_cost", 0), reverse=True)

    # 汇总
    total_cost = sum(r["data"].get("stat_cost", 0) for r in active)
    total_conv = sum(r["data"].get("attribution_convert_cnt", 0) for r in active)
    total_msg = sum(r["data"].get("attribution_message_action_cnt", 0) for r in active)
    total_intent = sum(r["data"].get("attribution_clue_confirm", 0) for r in active)
    total_intent_cost = total_cost / total_intent if total_intent > 0 else 0
    total_conv_cost = total_cost / total_conv if total_conv > 0 else 0

    # 表格列：账户名、消耗、转化、转化成本、私信、意向、意向成本
    cols = ["账户名", "消耗", "转化", "转化成本", "私信", "意向", "意向成本"]
    col_widths = [100, 75, 50, 70, 50, 50, 75]
    row_h = 34
    header_h = 40
    title_h = 45
    margin = 10
    width = sum(col_widths) + margin * 2
    height = title_h + header_h + (len(active) + 1) * row_h + 20

    # 创建图片
    img = Image.new('RGB', (width, height), '#FFFFFF')
    draw = ImageDraw.Draw(img)

    # 字体
    try:
        font_title = ImageFont.truetype("C:/Windows/Fonts/msyhbd.ttc", 18)
        font_header = ImageFont.truetype("C:/Windows/Fonts/msyhbd.ttc", 13)
        font_normal = ImageFont.truetype("C:/Windows/Fonts/msyh.ttc", 13)
        font_bold = ImageFont.truetype("C:/Windows/Fonts/msyhbd.ttc", 13)
    except:
        font_title = ImageFont.load_default()
        font_header = ImageFont.load_default()
        font_normal = ImageFont.load_default()
        font_bold = ImageFont.load_default()

    y = 8
    # 标题
    draw.text((10, y), f"📊 巨量本地推盯盘 {now_str}", fill='#1a73e8', font=font_title)
    y += title_h

    table_top = y

    # 表头背景
    draw.rectangle([margin, y, width - margin, y + header_h], fill='#e3f2fd')

    # 表头文字（居中）
    x = margin
    for i, col in enumerate(cols):
        bbox = draw.textbbox((0, 0), col, font=font_header)
        tw = bbox[2] - bbox[0]
        tx = x + (col_widths[i] - tw) / 2
        draw.text((tx, y + 11), col, fill='#1976d2', font=font_header)
        x += col_widths[i]
    y += header_h

    # 数据行
    for r in active:
        name = r["name"]
        d = r["data"]
        cost = d.get("stat_cost", 0) or 0
        conv = d.get("attribution_convert_cnt", 0) or 0
        conv_cost = d.get("attribution_convert_cost", 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

        vals = [
            name,
            f"¥{cost:.0f}",
            str(conv),
            f"¥{conv_cost:.0f}" if conv > 0 else "-",
            str(msg),
            str(intent),
            f"¥{intent_cost:.0f}" if intent > 0 else "-",
        ]

        # 意向成本超300标红
        text_color = '#333333'
        if intent > 0 and intent_cost > threshold:
            text_color = '#d32f2f'

        x = margin
        for i, val in enumerate(vals):
            bbox = draw.textbbox((0, 0), val, font=font_normal)
            tw = bbox[2] - bbox[0]
            tx = x + (col_widths[i] - tw) / 2
            draw.text((tx, y + 9), val, fill=text_color, font=font_normal)
            x += col_widths[i]
        # 行之间加横线
        draw.line([(margin, y + row_h), (width - margin, y + row_h)], fill='#e0e0e0', width=1)
        y += row_h

    # 合计行
    draw.rectangle([margin, y, width - margin, y + row_h], fill='#f5f5f5')
    totals = [
        "合计",
        f"¥{total_cost:.0f}",
        str(total_conv),
        f"¥{total_conv_cost:.0f}",
        str(total_msg),
        str(total_intent),
        f"¥{total_intent_cost:.0f}",
    ]
    x = margin
    for i, val in enumerate(totals):
        bbox = draw.textbbox((0, 0), val, font=font_bold)
        tw = bbox[2] - bbox[0]
        tx = x + (col_widths[i] - tw) / 2
        draw.text((tx, y + 9), val, fill='#333333', font=font_bold)
        x += col_widths[i]
    table_bottom = y + row_h

    # 画表格线
    line_color = '#cccccc'
    # 外框横线
    draw.line([(margin, table_top), (width - margin, table_top)], fill=line_color, width=1)
    draw.line([(margin, table_bottom), (width - margin, table_bottom)], fill=line_color, width=1)
    # 表头下横线
    draw.line([(margin, table_top + header_h), (width - margin, table_top + header_h)], fill='#1976d2', width=1)
    # 合计上横线
    draw.line([(margin, table_bottom - row_h), (width - margin, table_bottom - row_h)], fill=line_color, width=1)
    # 竖线
    x = margin
    for i in range(len(cols) + 1):
        draw.line([(x, table_top), (x, table_bottom)], fill=line_color, width=1)
        if i < len(cols):
            x += col_widths[i]

    # 保存为base64
    import base64
    import io
    buf = io.BytesIO()
    img.save(buf, format='PNG')
    img_bytes = buf.getvalue()
    img_b64 = base64.b64encode(img_bytes).decode('utf-8')
    import hashlib
    img_md5 = hashlib.md5(img_bytes).hexdigest()
    return img_b64, img_md5


def generate_budget_image(results, budgets, now_str):
    """生成预算表格图片：账户名、已消耗、日预算、剩余、备注"""
    font_path = r"C:\Windows\Fonts\msyh.ttc"
    font_title = ImageFont.truetype(font_path, 18)
    font_header = ImageFont.truetype(font_path, 14)
    font_normal = ImageFont.truetype(font_path, 13)
    font_bold = ImageFont.truetype(font_path, 13)

    # 准备数据行
    rows = []
    for r in results:
        name = r["name"]
        data = r["data"]
        cost = float(data.get("stat_cost", 0))
        bid = r["id"]
        binfo = budgets.get(str(bid), {})
        budget = binfo.get("budget", 0)
        bmode = binfo.get("budget_mode", "")
        if bmode == "BUDGET_MODE_INFINITE" or budget == 0:
            budget_str = "不限"
            remain_str = "-"
            note = ""
        else:
            remain = budget - cost
            budget_str = f"¥{round(budget)}"
            remain_str = f"¥{round(remain)}"
            note = "⚠️剩余<¥1000" if remain < 1000 else ""
        rows.append([name, f"¥{round(cost)}", budget_str, remain_str, note])

    # 按消耗从高到低排序
    rows.sort(key=lambda x: float(x[1].replace("¥", "")), reverse=True)

    # 合计行
    total_cost = sum(float(r["data"].get("stat_cost", 0)) for r in results)
    rows.append(["合计", f"¥{round(total_cost)}", "", "", ""])

    # 计算图片尺寸
    col_widths = [120, 100, 100, 100, 140]
    margin = 30
    header_h = 35
    row_h = 30
    title_h = 45
    width = sum(col_widths) + margin * 2
    height = title_h + header_h + len(rows) * row_h + margin * 2

    img = Image.new('RGB', (width, height), '#f5f7fa')
    draw = ImageDraw.Draw(img)

    # 标题
    title = f"📊 巨量本地推预算情况 {now_str}"
    bbox = draw.textbbox((0, 0), title, font=font_title)
    tw = bbox[2] - bbox[0]
    draw.text(((width - tw) / 2, 15), title, fill='#333333', font=font_title)

    y = title_h
    headers = ["账户名", "已消耗", "日预算", "剩余", "备注"]

    # 表头背景
    draw.rectangle([(margin, y), (width - margin, y + header_h)], fill='#4a90d9')
    x = margin
    for i, h in enumerate(headers):
        bbox = draw.textbbox((0, 0), h, font=font_header)
        tw = bbox[2] - bbox[0]
        tx = x + (col_widths[i] - tw) / 2
        draw.text((tx, y + 8), h, fill='white', font=font_header)
        x += col_widths[i]
    y += header_h

    # 数据行
    for ri, row in enumerate(rows):
        is_total = (ri == len(rows) - 1)
        if is_total:
            draw.rectangle([(margin, y), (width - margin, y + row_h)], fill='#e8f0fe')
        elif ri % 2 == 1:
            draw.rectangle([(margin, y), (width - margin, y + row_h)], fill='#ffffff')
        x = margin
        for i, val in enumerate(row):
            font_use = font_bold if is_total else font_normal
            color = '#333333'
            if i == 4 and val:
                color = '#e74c3c'
            bbox = draw.textbbox((0, 0), val, font=font_use)
            tw = bbox[2] - bbox[0]
            tx = x + (col_widths[i] - tw) / 2
            draw.text((tx, y + 7), val, fill=color, font=font_use)
            x += col_widths[i]
        y += row_h

    # 画表格线
    line_color = '#cccccc'
    # 横线
    draw.line([(margin, title_h), (width - margin, title_h)], fill=line_color, width=1)
    for i in range(len(rows) + 1):
        ly = title_h + header_h + i * row_h
        draw.line([(margin, ly), (width - margin, ly)], fill=line_color, width=1)
    # 竖线
    draw.line([(margin, title_h), (margin, y)], fill=line_color, width=1)
    x = margin
    for cw in col_widths:
        x += cw
        draw.line([(x, title_h), (x, y)], fill=line_color, width=1)

    import io, base64, hashlib
    buf = io.BytesIO()
    img.save(buf, format='PNG')
    img_bytes = buf.getvalue()
    img_b64 = base64.b64encode(img_bytes).decode()
    img_md5 = hashlib.md5(img_bytes).hexdigest()
    return img_b64, img_md5


def build_alert_text(results, threshold, now_str, budgets=None):
    """构建预警文字消息。"""
    if budgets is None:
        budgets = {}

    active = []
    for r in results:
        d = r["data"]
        if "error" in d:
            continue
        if (d.get("stat_cost", 0) or 0) > 0:
            active.append(r)

    lines = []
    lines.append(f"🔔 巨量本地推盯盘预警 {now_str}")
    lines.append("")

    over_threshold = []
    no_conv = []
    no_intent = []
    good_perf = []
    for r in active:
        d = r["data"]
        cost = d.get("stat_cost", 0) or 0
        conv = d.get("attribution_convert_cnt", 0) or 0
        intent = d.get("attribution_clue_confirm", 0) or 0
        intent_cost = d.get("attribution_clue_confirm_cost", 0) or 0
        if intent > 0 and intent_cost > threshold:
            over_threshold.append((r["name"], intent_cost, intent, cost, r["id"]))
        if cost > 200 and conv == 0:
            no_conv.append((r["name"], cost))
        if cost > 300 and intent == 0:
            no_intent.append((r["name"], cost))
        if intent > 0 and 0 < intent_cost < threshold:
            good_perf.append((r["name"], intent_cost, cost, r["id"]))

    if over_threshold:
        lines.append(f"🔴 意向成本超¥{threshold}预警：")
        for name, cost, cnt, used, acc_id in over_threshold:
            binfo = budgets.get(acc_id, {})
            budget = binfo.get("budget", 0)
            bmode = binfo.get("budget_mode", "")
            if bmode == "BUDGET_MODE_INFINITE" or budget == 0:
                budget_txt = "预算不限"
            else:
                budget_txt = f"预算¥{budget:.0f}"
            lines.append(f"  {name}：¥{cost:.0f}（{cnt}个意向）已消耗¥{used:.0f}/{budget_txt}")
        lines.append("")

    if no_conv:
        lines.append("⚠️ 消耗超¥200无转化：")
        for name, cost in no_conv:
            lines.append(f"  {name}：消耗¥{cost:.0f} 转化0")
        lines.append("")

    if no_intent:
        lines.append("⚠️ 消耗超¥300无意向：")
        for name, cost in no_intent:
            lines.append(f"  {name}：消耗¥{cost:.0f} 意向0")
        lines.append("")

    if good_perf:
        lines.append("🟢 效果好可加预算（意向成本<¥300）：")
        for gname, icost, cost, acc_id in good_perf:
            binfo = budgets.get(acc_id, {})
            budget = binfo.get("budget", 0)
            bmode = binfo.get("budget_mode", "")
            if bmode == "BUDGET_MODE_INFINITE" or budget == 0:
                lines.append(f"  {gname}：意向成本¥{icost:.0f} 已消耗¥{cost:.0f}（预算不限）")
            else:
                remain = budget - cost
                warn = " ⚠️剩余<¥1000" if remain < 1000 else ""
                lines.append(f"  {gname}：意向成本¥{icost:.0f} 已消耗¥{cost:.0f}/预算¥{budget:.0f}{warn}")
        lines.append("")

    return "\n".join(lines)


def send_wechat_image(webhook, img_b64, img_md5):
    """发送图片消息到企业微信群机器人。"""
    payload = {
        "msgtype": "image",
        "image": {
            "base64": img_b64,
            "md5": img_md5,
        }
    }
    resp = requests.post(webhook, json=payload, timeout=30)
    return resp.json()


def send_wechat(webhook, content):
    """发送文本消息到企业微信群机器人。"""
    payload = {
        "msgtype": "text",
        "text": {"content": content},
    }
    resp = requests.post(webhook, json=payload, timeout=15)
    return resp.json()


def main():
    # 只在8:00-22:00推送，其他时间直接退出
    now_hour = datetime.now().hour
    if now_hour < 8 or now_hour >= 22:
        sys.exit(0)

    # 防重复锁：同一小时内只跑一次，防止任务计划重复触发
    # 注意：--query模式不检查这个锁，这是给整点推送用的
    is_query = "--query" in sys.argv
    if not is_query:
        lock_file = "monitor.lock"
        lock_hour = datetime.now().strftime("%Y%m%d%H")
        try:
            lf = open(lock_file, "a+")
            try:
                # 尝试拿文件锁，非阻塞
                msvcrt.locking(lf.fileno(), msvcrt.LK_NB, 1)
            except OSError:
                # 没拿到锁，说明另一个实例在运行，直接退出
                lf.close()
                sys.exit(0)
            # 拿到锁了，读取锁文件内容
            lf.seek(0)
            last_hour = lf.read().strip()
            if last_hour == lock_hour:
                # 这小时已经跑过了，直接退出
                msvcrt.locking(lf.fileno(), msvcrt.LK_UNLCK, 1)
                lf.close()
                sys.exit(0)
            # 写入当前小时
            lf.seek(0)
            lf.truncate()
            lf.write(lock_hour)
            lf.flush()
            msvcrt.locking(lf.fileno(), msvcrt.LK_UNLCK, 1)
            lf.close()
        except Exception as e:
            # 锁文件创建失败就不管了，继续运行
            print("Lock check error:", e)

    config = load_config()
    access_token = config["oceanengine_access_token"]
    webhook = config["wechat_webhook"]
    threshold = config.get("intention_cost_threshold", 300)
    accounts = load_accounts()

    if "在此填入" in access_token:
        print("ERROR: 请先在 config.json 中填入 oceanengine_access_token")
        sys.exit(1)

    today = datetime.now().strftime("%Y-%m-%d")
    now_str = datetime.now().strftime("%Y-%m-%d %H:%M")

    # --query 模式下显示具体时分，整点推送模式下显示整点
    if "--query" not in sys.argv:
        now_str = datetime.now().strftime("%Y-%m-%d %H:00")

    results = []
    is_query = "--query" in sys.argv
    for i, acc in enumerate(accounts):
        if i > 0:
            time.sleep(0.5)  # 避免触发API频率限制
        data = fetch_account_report(access_token, acc["id"], today, today)
        results.append({"id": acc["id"], "name": acc["name"], "data": data})
        if not is_query:
            print(f"  {acc['name']}: {data}")

    # 批量获取账户预算
    acc_ids = [acc["id"] for acc in accounts]
    budgets = fetch_budgets(access_token, acc_ids)

    # 生成预警文字
    alert_text = build_alert_text(results, threshold, now_str, budgets)

    # 生成表格图片
    img_b64, img_md5 = generate_table_image(results, threshold, now_str, budgets)

    # 模式判断：--query 模式只输出文字和保存图片，不推送
    if "--query" in sys.argv:
        # 输出预警文字到stdout（PHP读取这个）
        print("===ALERT_TEXT_START===")
        print(alert_text)
        print("===ALERT_TEXT_END===")
        # 保存图片到文件
        import base64
        img_bytes = base64.b64decode(img_b64)
        with open("query_table.png", "wb") as f:
            f.write(img_bytes)
        print("===IMG_SAVED===")
        sys.exit(0)

    # --budget 模式：生成预算表格图片，不推送
    if "--budget" in sys.argv:
        img_b64_b, img_md5_b = generate_budget_image(results, budgets, now_str)
        import base64
        img_bytes = base64.b64decode(img_b64_b)
        with open("budget_table.png", "wb") as f:
            f.write(img_bytes)
        print("===BUDGET_IMG_SAVED===")
        sys.exit(0)

    # 整点推送模式：先发预警文字
    result1 = send_wechat(webhook, alert_text)
    print(f"预警文字推送结果: {result1}")

    # 再发表格图片
    result2 = send_wechat_image(webhook, img_b64, img_md5)
    print(f"表格图片推送结果: {result2}")

    if result1.get("errcode") != 0 or result2.get("errcode") != 0:
        sys.exit(1)


if __name__ == "__main__":
    main()
