# -*- coding: utf-8 -*-
"""
巨量本地推整点盯盘脚本
每整点拉取各账户消耗、转化、私信咨询、确认意向等数据，推送到企业微信群。
确认意向成本超过阈值的账户会重点标红提醒。
"""
import json
import os
import sys
import time
import tempfile
from datetime import datetime, timedelta
from urllib.parse import urlencode

import requests

from PIL import Image, ImageDraw, ImageFont
import openpyxl  # 账户列表统一从 账户简称.xlsx 读取

# 修复Windows控制台编码问题（无控制台模式下 sys.stdout 可能为 None，需容错）
if sys.platform == 'win32':
    try:
        sys.stdout.reconfigure(encoding='utf-8', errors='replace')
    except Exception:
        pass

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")
XLSX_PATH = os.path.join(APP_DIR, "账户简称.xlsx")  # 账户列表唯一数据源
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_from_xlsx(xlsx_path):
    """从 账户简称.xlsx 读取账户列表。

    表格结构（3列）：
        A列=账户名称(全名)  B列=账户ID(形如 "ID：1873920769881291")  C列=简称(展示用)
    返回 [{"id": "1873...", "name": "简称"}, ...]
    """
    wb = openpyxl.load_workbook(xlsx_path, data_only=True)
    ws = wb.active
    accounts = []
    for row in ws.iter_rows(min_row=2, values_only=True):
        cells = list(row) + [None, None, None]
        full_name, id_raw, short_name = cells[0], cells[1], cells[2]
        if id_raw is None:
            continue
        # B列可能为 "ID：1873920769881291" 或纯数字
        id_str = str(id_raw).replace("ID：", "").replace("ID:", "").replace("：", "").strip()
        name = (str(short_name).strip() if short_name is not None else "") or \
               (str(full_name).strip() if full_name is not None else "")
        if id_str:
            accounts.append({"id": id_str, "name": name})
    return accounts


def load_accounts(config):
    """账户优先从 账户简称.xlsx 读取；xlsx 缺失时回退到 config.json 的 accounts。"""
    if os.path.exists(XLSX_PATH):
        try:
            accs = load_accounts_from_xlsx(XLSX_PATH)
            if accs:
                return accs
            print("账户简称.xlsx 未读到账户，回退到 config.json")
        except Exception as e:
            print(f"读取 账户简称.xlsx 失败，回退到 config.json: {e}")
    return config.get("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 update_account_budget(access_token, account_id, budget, effective="EFFECTIVE_NOW", mode="BUDGET_MODE_DAY"):
    """修改单个本地推账户的日预算（立即生效 + 指定日预算）。"""
    url = "https://api.oceanengine.com/open_api/v3.0/local/budget/update/"
    headers = {"Access-Token": access_token, "Content-Type": "application/json"}
    payload = {
        "local_account_id": int(account_id),
        "effective_mode": effective,
        "budget_mode": mode,
        "budget": float(budget),
    }
    try:
        resp = requests.post(url, headers=headers, json=payload, timeout=30)
        return resp.status_code, resp.json()
    except Exception as e:
        return 0, {"code": -1, "message": f"请求异常: {e}"}


def read_budget_single(access_token, account_id):
    """读取单个账户当前预算（改前/改后回读用）。"""
    budgets = fetch_budgets(access_token, [account_id])
    return budgets.get(str(account_id))


def resolve_account(term, accounts=None):
    """按简称（去空格、忽略大小写）或账户ID精确匹配账户。匹配不到返回 None。"""
    if accounts is None:
        accounts = load_accounts(load_config())
    term_norm = "".join(str(term).split()).lower()
    # 先按 ID 精确匹配
    for a in accounts:
        if term_norm == str(a["id"]):
            return a
    # 再按简称精确匹配（去空格）
    for a in accounts:
        if term_norm == "".join(str(a["name"]).split()).lower():
            return a
    return None


def _run_budget_mode():
    """--budget：查询所有账户今日消耗 + 预算，只输出有消耗账户。"""
    config = load_config()
    access_token = config["oceanengine_access_token"]
    accounts = load_accounts(config)
    today = datetime.now().strftime("%Y-%m-%d")
    results = []
    for acc in accounts:
        data = fetch_account_report(access_token, acc["id"], today, today)
        results.append({"id": acc["id"], "name": acc["name"], "data": data})
    budgets = fetch_budgets(access_token, [a["id"] for a in accounts])

    lines = [f"💰 各账户消耗与预算 {today}", "（仅显示有消耗账户）", ""]
    active = [r for r in results
              if "error" not in r["data"] and (r["data"].get("stat_cost", 0) or 0) > 0]
    if not active:
        lines.append("今日暂无消耗账户")
    for r in active:
        cost = r["data"].get("stat_cost", 0) or 0
        binfo = budgets.get(r["id"], {}) or {}
        budget = binfo.get("budget", 0)
        bmode = binfo.get("budget_mode", "")
        btxt = "预算不限" if (bmode == "BUDGET_MODE_INFINITE" or budget == 0) else f"预算¥{budget:.0f}"
        lines.append(f"{r['name']}：消耗¥{cost:.0f} {btxt}")
    text = "\n".join(lines)
    print("===BUDGET_TEXT_START===")
    print(text)
    print("===BUDGET_TEXT_END===")


def _run_update_mode(term, amount):
    """--update-budget <简称或ID> <金额>：解析→校验→改预算→回读，输出 JSON。"""
    def emit(obj):
        print("===BUDGET_UPDATE_START===")
        print(json.dumps(obj, ensure_ascii=False))
        print("===BUDGET_UPDATE_END===")

    accounts = load_accounts(load_config())
    acc = resolve_account(term, accounts)
    if acc is None:
        emit({"ok": False, "term": term,
              "error": "未匹配到账户，请使用简称。可用：" + "、".join(sorted({a["name"] for a in accounts}))})
        return
    try:
        amt = float(amount)
    except (TypeError, ValueError):
        emit({"ok": False, "account": acc["name"], "account_id": acc["id"],
              "error": "金额格式错误，应为数字（如 3333）"})
        return
    if amt <= 0:
        emit({"ok": False, "account": acc["name"], "account_id": acc["id"],
              "error": "金额必须大于 0"})
        return

    config = load_config()
    token = config["oceanengine_access_token"]
    before = read_budget_single(token, acc["id"])
    status, resp = update_account_budget(token, acc["id"], amt)
    after = read_budget_single(token, acc["id"])
    emit({
        "ok": (resp.get("code") == 0),
        "account": acc["name"],
        "account_id": acc["id"],
        "amount_requested": amt,
        "budget_before": before,
        "budget_after": after,
        "api_code": resp.get("code"),
        "api_message": resp.get("message"),
    })


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):
    """生成盯盘表格图片——仅展示「有消耗」的账户明细 + 合计。

    与文字预警口径一致：只显示 stat_cost > 0 的账户，0 消耗的账户不展示，
    避免整点推送里混入一堆 ¥0 行。整点前已等待 fetch_delay 分钟让数据上报，
    所以「有消耗但整点瞬间没抓到」的情况基本不会出现。
    """
    if budgets is None:
        budgets = {}

    # 只显示有消耗的账户（与文字预警口径一致）
    rows = []
    for r in results:
        d = r["data"]
        if "error" in d:
            continue
        if (d.get("stat_cost", 0) or 0) > 0:
            rows.append(r)

    # 按消耗从高到低排序
    rows.sort(key=lambda x: x["data"].get("stat_cost", 0), reverse=True)

    # 汇总
    total_cost = sum(r["data"].get("stat_cost", 0) for r in rows)
    total_conv = sum(r["data"].get("attribution_convert_cnt", 0) for r in rows)
    total_msg = sum(r["data"].get("attribution_message_action_cnt", 0) for r in rows)
    total_intent = sum(r["data"].get("attribution_clue_confirm", 0) for r in rows)
    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

    # 字体（先建字体，便于估算预警文字换行与图片高度）
    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()

    warn_block_h = 0

    height = title_h + warn_block_h + header_h + (len(rows) + 1) * row_h + 20

    # 创建图片
    img = Image.new('RGB', (width, height), '#FFFFFF')
    draw = ImageDraw.Draw(img)

    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 rows:
        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 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"\U0001F514 巨量本地推盯盘预警 {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"\U0001F534 意向成本超\u00A5{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"预算\u00A5{budget:.0f}"
            lines.append(f"  {name}：\u00A5{cost:.0f}（{cnt}个意向）已消耗\u00A5{used:.0f}/{budget_txt}")
        lines.append("")

    if no_conv:
        lines.append("\u26A0\uFE0F 消耗超\u00A5200无转化：")
        for name, cost in no_conv:
            lines.append(f"  {name}：消耗\u00A5{cost:.0f} 转化0")
        lines.append("")

    if no_intent:
        lines.append("\u26A0\uFE0F 消耗超\u00A5300无意向：")
        for name, cost in no_intent:
            lines.append(f"  {name}：消耗\u00A5{cost:.0f} 意向0")
        lines.append("")

    if good_perf:
        lines.append(f"\U0001F7E2 效果好可加预算（意向成本<\u00A5300）：")
        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}：意向成本\u00A5{icost:.0f} 已消耗\u00A5{cost:.0f}（预算不限）")
            else:
                remain = budget - cost
                warn = " \u26A0\uFE0F剩余<\u00A51000" if remain < 1000 else ""
                lines.append(f"  {gname}：意向成本\u00A5{icost:.0f} 已消耗\u00A5{cost:.0f}/预算\u00A5{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():
    is_query = "--query" in sys.argv
    is_budget = "--budget" in sys.argv
    is_update = "--update-budget" in sys.argv
    is_manual = is_query or is_budget or is_update

    now = datetime.now()

    # 手动模式（被 PHP 调用）：仅输出不推送，不受整点窗口/锁/休眠限制
    if is_budget:
        _run_budget_mode()
        sys.exit(0)
    if is_update:
        idx = sys.argv.index("--update-budget")
        term = sys.argv[idx + 1] if len(sys.argv) > idx + 1 else ""
        amount = sys.argv[idx + 2] if len(sys.argv) > idx + 2 else ""
        _run_update_mode(term, amount)
        sys.exit(0)

    # 推送时间窗口：整点 :00 推送（任务计划在整点前约 50 分触发，先抓取，再休眠到整点推送）。
    # 仅当"推送目标整点"落在 8:00–22:00 才运行（即触发小时 7–21 时允许），
    # 这样每天首推 08:00、末推 22:00（22:00 为最后一条）。
    # --query / --budget / --update-budget 等手动模式不受此窗口限制，可随时手动跑。
    if not is_manual:
        if now.hour < 7 or now.hour >= 22:
            sys.exit(0)

    # 推送目标整点 = 下一个 :00（抓取已在整点前完成，数据完整，不会漏掉延迟上报的账户）
    push_dt = now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)

    # 防重复锁：按"推送目标整点"加锁，确保同一个整点只推送一次，
    # 防止任务计划重复触发 / 多份 exe 副本 / 手动重复点击造成"整点推两遍"。
    # 锁放在系统临时目录（机器级共享），跨 exe 副本也只推一次。
    if not is_manual:
        lock_path = os.path.join(tempfile.gettempdir(), "juliang_monitor_hourly.lock")
        lock_key = push_dt.strftime("%Y%m%d%H")
        try:
            # 原子创建锁文件：若已存在（同整点已跑 / 另一实例正在跑），直接退出
            fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
            os.write(fd, lock_key.encode("utf-8"))
            os.close(fd)
        except FileExistsError:
            # 锁文件已存在
            try:
                with open(lock_path, "r", encoding="utf-8") as f:
                    last_key = f.read().strip()
            except Exception:
                last_key = ""
            if last_key == lock_key:
                # 这个整点已经推送过了，直接退出（防重复推送）
                sys.exit(0)
            # 是上一个整点留下的旧锁，替换成当前整点
            try:
                os.remove(lock_path)
                fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
                os.write(fd, lock_key.encode("utf-8"))
                os.close(fd)
            except FileExistsError:
                # 极小概率并发：另一实例刚重建了，也退出，避免重复
                sys.exit(0)
        except Exception as e:
            # 极端情况下锁创建失败，打印一次并继续（不阻断推送）
            print("Lock check warning:", e)

    config = load_config()
    access_token = config["oceanengine_access_token"]
    webhook = config["wechat_webhook"]
    threshold = config.get("intention_cost_threshold", 300)
    accounts = load_accounts(config)
    print(f"已加载 {len(accounts)} 个账户（数据源：账户简称.xlsx，缺失时回退 config.json）")

    if "在此填入" in access_token:
        print("ERROR: 请先在 config.json 中填入 oceanengine_access_token")
        sys.exit(1)

    today = now.strftime("%Y-%m-%d")

    # ===== 整点前抓取（数据已上报完整，避免"只抓到一部分"）=====
    results = []
    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)

    # ===== 休眠到整点再推送（抓取在整点前完成，推送精确落在 :00）=====
    if not is_manual:
        sleep_secs = (push_dt - datetime.now()).total_seconds()
        if sleep_secs > 0:
            print(f"抓取完成，休眠 {sleep_secs:.0f}s 至 {push_dt:%Y-%m-%d %H:%M} 整点推送…")
            time.sleep(sleep_secs)

    # 整点推送模式下标题显示整点；--query 模式显示具体时分
    if is_query:
        now_str = now.strftime("%Y-%m-%d %H:%M")
    else:
        now_str = push_dt.strftime("%Y-%m-%d %H:00")

    # 生成预警文字（--query 模式会输出；整点推送仍单独发文字）
    alert_text = build_alert_text(results, threshold, now_str, budgets)

    # 生成表格图片（仅含"有消耗"账户，与文字预警口径一致）
    img_b64, img_md5 = generate_table_image(results, threshold, now_str, budgets)

    # 模式判断：--query 模式只输出文字和保存图片，不推送
    if is_query:
        # 输出预警文字到stdout（PHP读取这个）
        print("===ALERT_TEXT_START===")
        print(alert_text)
        print("===ALERT_TEXT_END===")
        # 保存图片到文件（固定写到 exe 所在目录，避免任务计划 cwd 不同导致找不到）
        import base64
        img_bytes = base64.b64decode(img_b64)
        img_path = os.path.join(APP_DIR, "query_table.png")
        with open(img_path, "wb") as f:
            f.write(img_bytes)
        # 同时把预警文字存成 txt，方便手动在命令行跑 --query 时查看结果（无控制台也不怕看不到）
        with open(os.path.join(APP_DIR, "query_text.txt"), "w", encoding="utf-8") as f:
            f.write(alert_text)
        print("===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()
