import requests
from datetime import datetime
from pwauto.utils.logger import logger


class FeishuNotifier:
    """飞书 Webhook 机器人通知"""

    def __init__(self, webhook_url: str):
        self.webhook_url = webhook_url

    def send_test_report(self, summary: dict):
        total = summary.get("total", 0)
        passed = summary.get("passed", 0)
        failed = summary.get("failed", 0)
        error = summary.get("error", 0)
        
        # 场景 1：致命问题（没跑完、0 用例、或者前置夹具报错）
        if total == 0 or error > 0:
            status = "❌ 运行失败"
        
        # 场景 2：业务 Bug（框架正常跑完了，但有红叉用例）
        elif failed > 0:
            status = "⚠️ 存在失败"
        
        # 场景 3：完美收官（总数大于 0，且没有任何失败和报错）
        else:
            status = "✅ 全部通过"

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

        content = [
            [{"tag": "text", "text": f"环境: {summary.get('env', '-')}  |  耗时: {summary['duration']:.1f}s"}],
            [{"tag": "text", "text": f"通过: {passed}  |  失败: {failed}  |  总数: {total}"}],
            [{"tag": "text", "text": f"时间: {now}"}],
        ]

        payload = {
            "msg_type": "post",
            "content": {
                "post": {
                    "zh_cn": {
                        "title": f"自动化测试报告 {status}",
                        "content": content
                    }
                }
            }
        }

        try:
            resp = requests.post(self.webhook_url, json=payload, timeout=10)
            resp.raise_for_status()
            logger.info("Feishu notification sent successfully.")
        except Exception as e:
            logger.error(f"Failed to send Feishu notification: {e}")