# -*- coding: utf-8 -*-
"""Bark 推送通知"""

from __future__ import annotations

import json
from urllib.parse import urlencode

import requests

from . import config


def send(title: str, body: str, group: str | None = None) -> bool:
    """发送 Bark 推送通知。

    优先使用 POST JSON 方式，失败时回退到 GET 方式。

    Args:
        title: 通知标题
        body: 通知正文
        group: 分组（默认使用 config.BARK_GROUP）

    Returns:
        True 发送成功，False 发送失败
    """
    group = group or config.BARK_GROUP
    base = config.BARK_URL.rstrip("/")

    # 方式1: POST JSON（推荐，避免 URL 编码问题）
    try:
        resp = requests.post(
            base,
            json={"title": title, "body": body, "group": group},
            timeout=5.0,
        )
        if resp.status_code == 200:
            return True
    except Exception:
        pass

    # 方式2: GET 回退（标题/正文做 URL 编码）
    try:
        params = {"group": group}
        # Bark GET 格式: {base}/{title}/{body}
        from urllib.parse import quote
        url = f"{base}/{quote(title)}/{quote(body)}?{urlencode(params)}"
        resp = requests.get(url, timeout=5.0)
        return resp.status_code == 200
    except Exception:
        return False


def send_crawl_result(
    trade_date: str,
    board_results: list[dict],
    success: bool,
    error_msg: str = "",
) -> bool:
    """发送抓取结果通知。

    Args:
        trade_date: 交易日期
        board_results: 各板块结果列表，每项 {"board_id", "label", "matched", "records", "status"}
        success: 整体是否成功
        error_msg: 失败时的错误信息

    Returns:
        True 发送成功
    """
    if success:
        title = f"每日行情抓取成功 {trade_date}"
        lines = []
        total_matched = 0
        total_records = 0
        for r in board_results:
            status_icon = "✅" if r["status"] == "done" else "⚠️" if r["status"] == "empty" else "❌"
            lines.append(
                f"{status_icon} {r['label']}({r['board_id']}): "
                f"匹配{r['matched']}帖, 解析{r['records']}条"
            )
            total_matched += r["matched"]
            total_records += r["records"]
        lines.append(f"\n合计: 匹配{total_matched}帖, 解析{total_records}条")
        body = "\n".join(lines)
    else:
        title = f"每日行情抓取失败 {trade_date}"
        body = error_msg or "抓取过程中发生错误"

    return send(title, body)
