"""
防封模块 — 风控告警推送
当触发日限额耗尽、指纹碰撞、操作时段违规、连续失败等事件时自动推送到飞书群。
包含冷却机制防止重复告警刷屏。
"""

import json
import logging
import time
from typing import Optional

logger = logging.getLogger(__name__)

FEISHU_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/d0f607da-ae26-43a0-9dbe-2c2c0b90743d"

ALERT_COOLDOWN = 300
_last_alert_ts: dict = {}


def _can_alert(alert_key: str) -> bool:
    now = time.time()
    last = _last_alert_ts.get(alert_key, 0)
    if now - last < ALERT_COOLDOWN:
        return False
    _last_alert_ts[alert_key] = now
    return True


async def send_alert(
    level: str,
    title: str,
    detail: str,
    device_id: Optional[str] = None,
    platform: Optional[str] = None,
):
    """
    发送风控告警到飞书群。
    level: "warning" | "critical" | "info"
    """
    alert_key = f"{level}:{title}:{device_id or 'global'}"
    if not _can_alert(alert_key):
        logger.debug(f"[告警冷却中] {alert_key}")
        return

    icon = {"critical": "🚨", "warning": "⚠️", "info": "ℹ️"}.get(level, "📢")
    text = (
        f"{icon}【工作手机·风控告警】\n\n"
        f"级别：{level.upper()}\n"
        f"事件：{title}\n"
    )
    if device_id:
        text += f"设备：{device_id}\n"
    if platform:
        text += f"平台：{platform}\n"
    text += f"详情：{detail}\n"
    text += f"时间：{time.strftime('%Y-%m-%d %H:%M:%S')}"

    color_map = {"critical": "red", "warning": "orange", "info": "blue"}
    card = {
        "header": {
            "template": color_map.get(level, "blue"),
            "title": {"content": f"{icon} 风控告警 · {title}", "tag": "plain_text"},
        },
        "elements": [
            {"tag": "div", "text": {"content": text, "tag": "lark_md"}},
        ],
    }
    payload = {"msg_type": "interactive", "card": card}
    try:
        import httpx
        async with httpx.AsyncClient(timeout=5) as client:
            resp = await client.post(FEISHU_WEBHOOK, json=payload)
            body = resp.json()
            if body.get("code") != 0:
                logger.warning(f"飞书告警发送失败: {body}")
    except ImportError:
        try:
            import urllib.request
            data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
            req = urllib.request.Request(
                FEISHU_WEBHOOK, data=data,
                headers={"Content-Type": "application/json; charset=utf-8"},
            )
            urllib.request.urlopen(req, timeout=5)
        except Exception as e:
            logger.warning(f"飞书告警发送失败(urllib): {e}")
    except Exception as e:
        logger.warning(f"飞书告警发送异常: {e}")


async def alert_daily_limit(device_id: str, platform: str, action: str, count: int, limit: int):
    await send_alert(
        "warning",
        "日操作上限已达",
        f"{platform}.{action} 当前 {count}/{limit}",
        device_id, platform,
    )


async def alert_fingerprint_collision(device_id: str, collided_with: list):
    await send_alert(
        "critical",
        "设备指纹碰撞",
        f"与设备 {collided_with} 指纹相同，存在关联封号风险",
        device_id,
    )


async def alert_outside_hours(device_id: str, action: str):
    await send_alert(
        "warning",
        "非操作时段操作",
        f"尝试在禁止时段执行 {action}",
        device_id,
    )


async def alert_sensitive_content(device_id: str, platform: str, keywords: list):
    await send_alert(
        "warning",
        "敏感内容拦截",
        f"检测到敏感词: {keywords[:5]}",
        device_id, platform,
    )


async def alert_consecutive_failures(device_id: str, platform: str, fail_count: int):
    await send_alert(
        "critical",
        "连续操作失败",
        f"连续失败 {fail_count} 次，建议暂停该设备操作",
        device_id, platform,
    )
