#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
每日资讯推送脚本
获取：Readhub、Github Trending、Hacker News、V2EX、Douban、空投项目
"""

import requests
import json
from datetime import datetime
import re

def get_readhub():
    """获取 Readhub 每日新闻"""
    try:
        # Readhub 每日新闻 API
        url = "https://api.readhub.cn/method/daily"
        headers = {"User-Agent": "Mozilla/5.0"}
        resp = requests.get(url, headers=headers, timeout=10)
        data = resp.json()
        
        news_list = []
        if 'data' in data and 'articles' in data['data']:
            for article in data['data']['articles'][:10]:
                title = article.get('title', '')
                url = article.get('url', '')
                news_list.append(f"• [{title}]({url})")
        
        return "\n".join(news_list) if news_list else "暂无数据"
    except Exception as e:
        return f"获取失败：{str(e)}"

def get_github_trending():
    """获取 Github Trending"""
    try:
        # 使用 GitHub Trends API
        url = "https://api.githubtrends.io/trending/daily"
        headers = {"User-Agent": "Mozilla/5.0"}
        resp = requests.get(url, headers=headers, timeout=10)
        data = resp.json()
        
        repos = []
        if isinstance(data, list):
            for repo in data[:10]:
                name = repo.get('name', '')
                desc = repo.get('description', '')[:50]
                stars = repo.get('stars', 0)
                repos.append(f"• ⭐ {name} - {desc}... ({stars}★)")
        
        return "\n".join(repos) if repos else "暂无数据"
    except Exception as e:
        return f"获取失败：{str(e)}"

def get_hacker_news():
    """获取 Hacker News 热门"""
    try:
        # 获取 Top Stories IDs
        top_url = "https://hacker-news.firebaseio.com/v0/topstories.json"
        resp = requests.get(top_url, timeout=10)
        ids = resp.json()[:10]
        
        stories = []
        for item_id in ids:
            item_url = f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json"
            item_resp = requests.get(item_url, timeout=5)
            item = item_resp.json()
            if item and 'title' in item:
                title = item['title']
                url = item.get('url', f"https://news.ycombinator.com/item?id={item_id}")
                score = item.get('score', 0)
                stories.append(f"• 🔥 {title} ({score} 分)")
        
        return "\n".join(stories) if stories else "暂无数据"
    except Exception as e:
        return f"获取失败：{str(e)}"

def get_v2ex_hot():
    """获取 V2EX 热帖"""
    try:
        url = "https://www.v2ex.com/api/hot.json"
        headers = {"User-Agent": "Mozilla/5.0"}
        resp = requests.get(url, headers=headers, timeout=10)
        data = resp.json()
        
        posts = []
        if isinstance(data, list):
            for post in data[:10]:
                title = post.get('title', '')
                url = post.get('url', '')
                replies = post.get('replies', 0)
                posts.append(f"• 💬 [{title}]({url}) ({replies} 回复)")
        
        return "\n".join(posts) if posts else "暂无数据"
    except Exception as e:
        return f"获取失败：{str(e)}"

def get_douban_movie():
    """获取 Douban 热门电影"""
    try:
        url = "https://movie.douban.com/j/search_subjects"
        params = {
            "type": "movie",
            "tag": "热门",
            "sort": "recommend",
            "page_limit": 10
        }
        headers = {"User-Agent": "Mozilla/5.0"}
        resp = requests.get(url, params=params, headers=headers, timeout=10)
        data = resp.json()
        
        movies = []
        if 'subjects' in data:
            for movie in data['subjects'][:10]:
                title = movie.get('title', '')
                url = movie.get('url', '')
                rate = movie.get('rate', 0)
                movies.append(f"• 🎬 [{title}]({url}) ⭐{rate}分")
        
        return "\n".join(movies) if movies else "暂无数据"
    except Exception as e:
        return f"获取失败：{str(e)}"

def get_airdrop_info():
    """获取空投项目信息"""
    try:
        # 使用 RSSHub 获取空投资讯
        url = "https://rsshub.app/airdrop"
        headers = {"User-Agent": "Mozilla/5.0"}
        resp = requests.get(url, headers=headers, timeout=10)
        
        # 解析 RSS XML
        items = re.findall(r'<item>(.*?)</item>', resp.text, re.DOTALL)
        airdrops = []
        for item in items[:5]:
            title_match = re.search(r'<title><!\[CDATA\[(.*?)\]\]>', item)
            link_match = re.search(r'<link>(.*?)</link>', item)
            if title_match and link_match:
                title = title_match.group(1)
                link = link_match.group(1)
                airdrops.append(f"• 🪂 [{title}]({link})")
        
        return "\n".join(airdrops) if airdrops else "暂无数据"
    except Exception as e:
        return f"获取失败：{str(e)}"

def get_karpathy_rss():
    """获取 Andrej Karpathy 推荐内容"""
    try:
        # Karpathy 的 Twitter/X 或博客
        # 这里使用他的博客 RSS（如果有）
        url = "https://karpathy.ai/feed.xml"
        headers = {"User-Agent": "Mozilla/5.0"}
        resp = requests.get(url, headers=headers, timeout=10)
        
        items = re.findall(r'<item>(.*?)</item>', resp.text, re.DOTALL)
        posts = []
        for item in items[:5]:
            title_match = re.search(r'<title>(.*?)</title>', item)
            link_match = re.search(r'<link>(.*?)</link>', item)
            if title_match and link_match:
                title = title_match.group(1)
                link = link_match.group(1)
                posts.append(f"• 🧠 [{title}]({link})")
        
        return "\n".join(posts) if posts else "暂无数据"
    except Exception as e:
        return f"获取失败：{str(e)}"

def generate_newsletter():
    """生成每日资讯简报"""
    today = datetime.now().strftime("%Y 年 %m 月 %d 日 %A")
    
    newsletter = f"""# 📰 每日资讯早报

**日期：** {today}
**生成时间：** {datetime.now().strftime("%H:%M")}

---

## 🧠 Andrej Karpathy 推荐
{get_karpathy_rss()}

---

## 🔥 Github Trending
{get_github_trending()}

---

## 📰 Hacker News 热门
{get_hacker_news()}

---

## 💬 V2EX 热帖
{get_v2ex_hot()}

---

## 🎬 Douban 热门影音
{get_douban_movie()}

---

## 🪂 近期空投项目
{get_airdrop_info()}

---

_祝您今天工作顺利！_ 🤖
"""
    return newsletter

if __name__ == "__main__":
    print(generate_newsletter())
