#!/usr/bin/env python3
"""
飞书推送工具
"""

import requests
import json
import datetime

class FeishuSender:
    """飞书消息发送器"""
    
    def __init__(self):
        # 飞书配置（从OpenClaw配置中获取）
        self.app_id = "cli_a94e174db1785bde"
        self.app_secret = "ly7LKuVeUTmllItRKipfbfxKrbpgrAwX"
        self.access_token = None
        self.get_access_token()
    
    def get_access_token(self):
        """获取飞书访问令牌"""
        url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
        headers = {"Content-Type": "application/json; charset=utf-8"}
        data = {
            "app_id": self.app_id,
            "app_secret": self.app_secret
        }
        
        try:
            response = requests.post(url, headers=headers, json=data, timeout=10)
            if response.status_code == 200:
                result = response.json()
                if result.get("code") == 0:
                    self.access_token = result.get("tenant_access_token")
                    print(f"✅ 飞书访问令牌获取成功")
                    return True
                else:
                    print(f"❌ 飞书令牌获取失败: {result}")
            else:
                print(f"❌ 飞书请求失败: {response.status_code}")
        except Exception as e:
            print(f"❌ 飞书连接异常: {e}")
        
        return False
    
    def send_markdown_message(self, user_id: str, title: str, content: str):
        """发送Markdown格式消息"""
        if not self.access_token:
            if not self.get_access_token():
                return False
        
        url = "https://open.feishu.cn/open-apis/im/v1/messages"
        params = {"receive_id_type": "user_id"}
        headers = {
            "Authorization": f"Bearer {self.access_token}",
            "Content-Type": "application/json; charset=utf-8"
        }
        
        # 构建消息内容
        message_content = {
            "config": {"wide_screen_mode": True},
            "header": {
                "title": {
                    "tag": "plain_text",
                    "content": title
                },
                "template": "blue"
            },
            "elements": [
                {
                    "tag": "markdown",
                    "content": content
                },
                {
                    "tag": "hr"
                },
                {
                    "tag": "note",
                    "elements": [
                        {
                            "tag": "plain_text",
                            "content": f"📊 情报大师 · {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
                        }
                    ]
                }
            ]
        }
        
        data = {
            "receive_id": user_id,
            "msg_type": "interactive",
            "content": json.dumps(message_content, ensure_ascii=False)
        }
        
        try:
            response = requests.post(url, params=params, headers=headers, json=data, timeout=10)
            if response.status_code == 200:
                result = response.json()
                if result.get("code") == 0:
                    print(f"✅ 飞书消息发送成功")
                    return True
                else:
                    print(f"❌ 飞书消息发送失败: {result}")
            else:
                print(f"❌ 飞书请求失败: {response.status_code}, {response.text}")
        except Exception as e:
            print(f"❌ 飞书发送异常: {e}")
        
        return False
    
    def send_text_message(self, user_id: str, text: str):
        """发送文本消息（备用）"""
        if not self.access_token:
            if not self.get_access_token():
                return False
        
        url = "https://open.feishu.cn/open-apis/im/v1/messages"
        params = {"receive_id_type": "user_id"}
        headers = {
            "Authorization": f"Bearer {self.access_token}",
            "Content-Type": "application/json; charset=utf-8"
        }
        
        data = {
            "receive_id": user_id,
            "msg_type": "text",
            "content": json.dumps({"text": text}, ensure_ascii=False)
        }
        
        try:
            response = requests.post(url, params=params, headers=headers, json=data, timeout=10)
            if response.status_code == 200:
                result = response.json()
                if result.get("code") == 0:
                    print(f"✅ 飞书文本消息发送成功")
                    return True
        except Exception as e:
            print(f"❌ 飞书文本发送异常: {e}")
        
        return False

def test_feishu_connection():
    """测试飞书连接"""
    print("测试飞书连接...")
    sender = FeishuSender()
    
    if sender.access_token:
        print("✅ 飞书连接测试成功")
        
        # 测试发送消息（给首长）
        test_user_id = "ou_499a5c731212b08e951a441a2bc8a82c"
        test_title = "情报大师测试消息"
        test_content = "**测试内容**\n\n这是情报大师的测试消息，确认飞书推送功能正常工作。\n\n✅ 连接正常\n📊 准备就绪"
        
        print(f"发送测试消息给用户: {test_user_id}")
        success = sender.send_markdown_message(test_user_id, test_title, test_content)
        
        if success:
            print("🎉 飞书推送测试完成！")
        else:
            print("⚠️ 消息发送失败，请检查配置")
        
        return success
    else:
        print("❌ 飞书连接测试失败")
        return False

if __name__ == "__main__":
    print("="*60)
    print("飞书推送功能测试")
    print("="*60)
    
    test_feishu_connection()