#!/usr/bin/env python3
"""Send brief link message to Discord RobotDaily channel."""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path

from utils import load_env, log


def send_digest_link(enriched: dict, hugo_url: str, dry_run: bool = False) -> str:
    """Send brief link message to Discord RobotDaily channel."""
    
    counts = enriched.get("counts", {})
    embodied = counts.get("embodied", 0)
    representation = counts.get("representation", 0)
    reinforcement = counts.get("reinforcement", 0)
    total = embodied + representation + reinforcement
    
    message = f"""📰 RobotDaily {enriched.get('date', 'today')}

今日精选 {total} 篇论文：
• 具身智能：{embodied} 篇
• 表征学习：{representation} 篇  
• 强化学习：{reinforcement} 篇

🔗 查看完整简报：
{hugo_url}

祝有充实的一天！✨"""

    if dry_run:
        log(f"[DRY RUN] 将要发送的消息：")
        log(message)
        return message

    # 读取环境配置
    env = load_env()
    discord_token = env.get("DISCORD_BOT_TOKEN", "")
    channel_id = env.get("DISCORD_ROBOTDAILY_CHANNEL_ID", "")
    
    if not discord_token:
        log("❌ 未设置 DISCORD_BOT_TOKEN")
        return ""
    
    if not channel_id:
        log("❌ 未设置 DISCORD_ROBOTDAILY_CHANNEL_ID")
        return ""

    # Discord API 发送消息
    import requests
    
    url = f"https://discord.com/api/v10/channels/{channel_id}/messages"
    headers = {
        "Authorization": f"Bot {discord_token}",
        "Content-Type": "application/json",
    }
    
    data = {"content": message}
    
    try:
        response = requests.post(url, json=data, headers=headers, timeout=10)
        response.raise_for_status()
        log(f"✅ 消息已发送到 Discord 频道 {channel_id}")
        return message
    except requests.exceptions.RequestException as e:
        log(f"❌ Discord 消息发送失败：{e}")
        return ""


def main():
    parser = argparse.ArgumentParser(description="Send brief link message to Discord")
    parser.add_argument("--hugo-url", required=True, help="Hugo 网站链接")
    parser.add_argument("--embodied", type=int, required=True, help="具身智能论文数量")
    parser.add_argument("--representation", type=int, required=True, help="表征学习论文数量")
    parser.add_argument("--reinforcement", type=int, required=True, help="强化学习论文数量")
    parser.add_argument("--total", type=int, required=True, help="总论文数量")
    parser.add_argument("--date", required=True, help="日期")
    parser.add_argument("--dry-run", action="store_true", help="dry run 模式")
    args = parser.parse_args()
    
    enriched = {
        "date": args.date,
        "counts": {
            "embodied": args.embodied,
            "representation": args.representation,
            "reinforcement": args.reinforcement,
        }
    }
    
    send_digest_link(enriched, args.hugo_url, args.dry_run)


if __name__ == "__main__":
    main()
