#!/usr/bin/env python3
"""
A 股早盘新闻播报脚本
每天早上 8:30 自动抓取并发送股市早市新闻
"""

import requests
from datetime import datetime
import json

# ============ 配置 ============

# 企业微信配置
WECOM_BOT_ID = "aibwl3AhnzfRPRTEZvBVwlB-vRD33yJdUVX"
WECOM_SECRET = "1eUB2yd2R7bll6VjBQ5OGptJj2YiwutMUmACe9UGC7k"
TARGET_USER = "HouHuan"  # 接收早报记者的用户

# 新闻源配置
NEWS_SOURCES = [
    {
        "name": "财联社",
        "url": "https://www.cls.cn/index",
        "type": "homepage"
    },
    {
        "name": "东方财富早盘",
        "url": "https://stock.eastmoney.com/",
        "type": "homepage"
    }
]

# ============ 功能函数 ============

def fetch_market_news():
    """获取早盘新闻摘要"""
    import subprocess
    
    # 搜索今日早盘新闻
    query = f"A 股 早盘 财经新闻 {datetime.now().strftime('%Y年%m月%d日')} 隔夜外盘 涨停复盘"
    
    try:
        result = subprocess.run(
            ['openclaw', 'web_search', '--query', query, '--count', '8'],
            capture_output=True,
            text=True,
            timeout=30
        )
        return result.stdout
    except Exception as e:
        print(f"新闻获取失败：{e}")
        return None

def fetch_overnight_markets():
    """获取隔夜外盘行情"""
    import subprocess
    
    query = "隔夜外盘 美股 道琼斯 纳斯达克 标普 中概股"
    
    try:
        result = subprocess.run(
            ['openclaw', 'web_search', '--query', query, '--count', '5'],
            capture_output=True,
            text=True,
            timeout=30
        )
        return result.stdout
    except Exception as e:
        print(f"外盘数据获取失败：{e}")
        return None

def generate_briefing():
    """生成早盘简报"""
    news = fetch_market_news()
    overnight = fetch_overnight_markets()
    
    if not news:
        return "❌ 新闻获取失败，请稍后重试"
    
    # 组合简报
    briefing = f"""📈【A 股早盘简报】{datetime.now().strftime('%Y-%m-%d %H:%M')}
━━━━━━━━━━━━━━━━━━━━

🌍 隔夜外盘
{overnight if overnight else '数据暂缺'}

┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈

📰 早盘要闻
{news}

┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈

💡 今日关注
• 开盘情绪：观察量能变化
• 热点板块：半导体/深海科技/农业
• 风险提示：避免追高，关注回调机会

┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈

⏰ 播报时间：{datetime.now().strftime('%H:%M')}
📊 数据来源：财联社、东方财富、新浪财经

祝您投资顺利！🦐
"""
    return briefing

def send_wecom_message(message):
    """发送企业微信消息"""
    from gateway import send_message
    
    try:
        send_message(
            channel="wecom",
            target=TARGET_USER,
            message=message
        )
        print(f"✅ 早报已发送给 {TARGET_USER}")
        return True
    except Exception as e:
        print(f"❌ 发送失败：{e}")
        return False

# ============ 主程序 ============

def main():
    """执行早盘播报"""
    print(f"\n{'='*60}")
    print(f"📈 A 股早盘新闻播报 - {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    print(f"{'='*60}")
    
    # 生成简报
    briefing = generate_briefing()
    
    # 发送消息
    success = send_wecom_message(briefing)
    
    print(f"{'='*60}\n")
    
    return success

if __name__ == "__main__":
    main()
