#!/usr/bin/env python3
import os
import json
import subprocess
import requests
from datetime import datetime
from dotenv import load_dotenv

load_dotenv()

# 配置
CHANGE_THRESHOLD = float(os.getenv("PM_REPORT_CHANGE_THRESHOLD", 10))
TOP_N = int(os.getenv("PM_REPORT_TOP_N", 15))
CACHE_FILE = os.path.join(os.path.dirname(__file__), "price_cache.json")
POLYCLAW_DIR = "/root/.agents/skills/polyclaw"
RECEIVE_ID = os.getenv("FEISHU_RECEIVE_ID", "ou_7c623036b45fe81f372b032da664a4fe")

def get_current_markets():
    """调用polyclaw获取当前市场数据"""
    cmd = [
        "uv", "run", "python", "scripts/markets.py",
        "--json", "trending"
    ]
    result = subprocess.run(
        cmd,
        cwd=POLYCLAW_DIR,
        capture_output=True,
        text=True
    )
    if result.returncode != 0:
        print(f"获取市场数据失败: {result.stderr}")
        return []
    try:
        return json.loads(result.stdout)
    except json.JSONDecodeError:
        print("解析市场数据失败")
        return []

def load_cache():
    """加载历史价格缓存"""
    if os.path.exists(CACHE_FILE):
        with open(CACHE_FILE, "r") as f:
            return json.load(f)
    return {}

def save_cache(markets):
    """保存当前价格到缓存"""
    cache = {}
    for market in markets:
        cache[market["id"]] = {
            "yes_price": market["yes"],
            "no_price": market["no"],
            "question": market["question"],
            "volume": market["volume_24h"],
            "timestamp": datetime.now().isoformat()
        }
    with open(CACHE_FILE, "w") as f:
        json.dump(cache, f, indent=2)

def calculate_changes(current_markets, old_cache):
    """计算价格变动"""
    changes = []
    for market in current_markets:
        market_id = market["id"]
        current_yes = float(market["yes"].replace("$", ""))
        current_vol = market["volume_24h"]
        
        if market_id in old_cache:
            old_yes = float(old_cache[market_id]["yes_price"].replace("$", ""))
            change_pct = ((current_yes - old_yes) / old_yes) * 100 if old_yes > 0 else 0
            changes.append({
                "id": market_id,
                "question": market["question"],
                "current_yes": current_yes,
                "current_no": float(market["no"].replace("$", "")),
                "old_yes": old_yes,
                "change_pct": round(change_pct, 2),
                "volume": current_vol
            })
        else:
            # 新市场
            changes.append({
                "id": market_id,
                "question": market["question"],
                "current_yes": current_yes,
                "current_no": float(market["no"].replace("$", "")),
                "old_yes": None,
                "change_pct": None,
                "volume": current_vol,
                "is_new": True
            })
    return changes

def translate_text(text):
    """翻译英文为中文"""
    try:
        url = "https://translate.googleapis.com/translate_a/single"
        params = {
            "client": "gtx",
            "sl": "en",
            "tl": "zh-CN",
            "dt": "t",
            "q": text
        }
        response = requests.get(url, params=params, timeout=10)
        if response.status_code == 200:
            result = response.json()
            return ''.join([item[0] for item in result[0]])
    except Exception as e:
        print(f"翻译失败: {e}")
        return "（翻译暂不可用）"

def generate_report(changes):
    """生成早报内容"""
    today = datetime.now().strftime("%Y-%m-%d")
    report = [f"📊 Polymarket 每日早报 | {today}", "="*40]
    
    # 筛选有变动的事件
    gainers = [c for c in changes if c.get("change_pct") is not None and c["change_pct"] >= CHANGE_THRESHOLD]
    losers = [c for c in changes if c.get("change_pct") is not None and c["change_pct"] <= -CHANGE_THRESHOLD]
    new_markets = [c for c in changes if c.get("is_new")]
    hot_markets = sorted(changes, key=lambda x: float(x["volume"].replace("$", "").replace("M", "").replace("K", "")) * (1e6 if "M" in x["volume"] else 1e3), reverse=True)[:5]
    
    if gainers:
        report.append("\n📈 涨幅Top事件（概率上升 ≥ {}%）：".format(CHANGE_THRESHOLD))
        gainers_sorted = sorted(gainers, key=lambda x: x["change_pct"], reverse=True)[:TOP_N]
        for i, g in enumerate(gainers_sorted, 1):
            question_cn = translate_text(g['question'])
            report.append(f"{i}. 🇺🇸 {g['question'][:80]}\n   🇨🇳 {question_cn}\n   👉 YES ${g['current_yes']:.2f} (+{g['change_pct']:.1f}% 24h) | 交易量 {g['volume']}")
    
    if losers:
        report.append("\n📉 跌幅Top事件（概率下降 ≥ {}%）：".format(CHANGE_THRESHOLD))
        losers_sorted = sorted(losers, key=lambda x: x["change_pct"])[:TOP_N]
        for i, l in enumerate(losers_sorted, 1):
            question_cn = translate_text(l['question'])
            report.append(f"{i}. 🇺🇸 {l['question'][:80]}\n   🇨🇳 {question_cn}\n   👉 YES ${l['current_yes']:.2f} ({l['change_pct']:.1f}% 24h) | 交易量 {l['volume']}")
    
    if new_markets:
        report.append("\n🆕 新增热门市场：")
        for i, m in enumerate(new_markets[:5], 1):
            question_cn = translate_text(m['question'])
            report.append(f"{i}. 🇺🇸 {m['question'][:80]}\n   🇨🇳 {question_cn}\n   👉 YES ${m['current_yes']:.2f} / NO ${m['current_no']:.2f} | 交易量 {m['volume']}")
    
    report.append("\n🔥 今日高交易量热门事件：")
    for i, m in enumerate(hot_markets, 1):
        question_cn = translate_text(m['question'])
        report.append(f"{i}. 🇺🇸 {m['question'][:80]}\n   🇨🇳 {question_cn}\n   👉 YES ${m['current_yes']:.2f} / NO ${m['current_no']:.2f} | 交易量 {m['volume']}")
    
    report.append("\n⚠️ 以上数据来自Polymarket，仅供参考，不构成投资建议。")
    return "\n".join(report)

def send_report(report_content):
    """发送早报到飞书"""
    # 调用feishu_im_user_message工具发送
    import json
    content = json.dumps({"text": report_content})
    cmd = [
        "openclaw", "tool", "run", "feishu_im_user_message",
        "--action", "send",
        "--receive_id_type", "open_id",
        "--receive_id", RECEIVE_ID,
        "--msg_type", "text",
        "--content", content
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"发送消息失败: {result.stderr}")
        return False
    print("早报发送成功")
    return True

def main():
    print("开始生成Polymarket每日早报...")
    current_markets = get_current_markets()
    if not current_markets:
        print("未获取到市场数据，退出")
        return
    
    old_cache = load_cache()
    changes = calculate_changes(current_markets, old_cache)
    report = generate_report(changes)
    print("\n生成的早报内容：")
    print(report)
    
    send_report(report)
    save_cache(current_markets)
    print("早报生成完成")

if __name__ == "__main__":
    main()
