#!/usr/bin/env python3
"""
Format paper information into Telegram-friendly cards
"""

import json
import sys
from urllib.parse import quote


def format_paper_card(paper):
    """
    Format a single paper into a Telegram message card
    """
    title = paper['title']
    authors = ', '.join(paper['authors'][:3])  # First 3 authors
    if len(paper['authors']) > 3:
        authors += ' et al.'
    
    abstract = paper['abstract'][:500] + '...' if len(paper['abstract']) > 500 else paper['abstract']
    
    # Create tags
    tags = ' '.join([f"#{tag.replace('-', '').replace('_', '')[:20]}" for tag in paper.get('tags', [])[:5]])
    
    # Create DOI link
    doi_link = paper.get('doi', '')
    if doi_link:
        doi_url = f"https://doi.org/{doi_link}" if not doi_link.startswith('http') else doi_link
        doi_part = f"\n📄 [DOI链接]({doi_url})"
    else:
        doi_part = f"\n📄 [论文链接]({paper.get('url', '')})"
    
    # Format the card
    card = f"""📄 **{title}**
✍️ {authors}

📋 **摘要**: {abstract}

🏷️ **标签**: {tags}{doi_part}
"""
    return card


def main():
    # Read JSON input from stdin
    input_text = sys.stdin.read().strip()
    
    if not input_text:
        print("No input provided", file=sys.stderr)
        sys.exit(1)
    
    try:
        papers = json.loads(input_text)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON input: {e}", file=sys.stderr)
        sys.exit(1)
    
    # Format each paper as a card
    cards = []
    for i, paper in enumerate(papers):
        card = format_paper_card(paper)
        cards.append(card)
    
    # Combine all cards
    daily_digest = f"""🤖 每日AI前沿速递 - {papers[0]['published'][:10] if papers else ''}

{'\n---\n'.join(cards)}

⏰ 每日定时推送，助您掌握最新研究动态
"""
    
    print(daily_digest)


if __name__ == "__main__":
    main()