"""
Показать топ-посты из базы данных
Проверка что демо-посты созданы и бот будет работать
"""

from datetime import datetime, timedelta
from sqlalchemy import desc
from src.database.db import get_session
from src.database.models import Post, Source, PostMetrics

def show_top_posts(limit=10):
    """Показать топ-посты по normalized_score"""
    
    print("=" * 80)
    print("TOP POSTS FROM DATABASE")
    print("=" * 80)
    
    session = get_session()
    
    try:
        # Get top posts by score
        top_posts = (
            session.query(Post)
            .join(PostMetrics)
            .join(Source)
            .order_by(desc(PostMetrics.normalized_score))
            .limit(limit)
            .all()
        )
        
        if not top_posts:
            print("\n! NO POSTS FOUND IN DATABASE")
            print("\nRun this command to create demo posts:")
            print("  python create_demo_posts.py")
            return
        
        print(f"\nFound {len(top_posts)} posts")
        print("-" * 80)
        
        for i, post in enumerate(top_posts, 1):
            source = post.source
            metrics = post.metrics
            
            # Format date
            created_str = post.created_at.strftime("%Y-%m-%d %H:%M") if post.created_at else "N/A"
            
            # Format content
            content = post.content[:60] + "..." if len(post.content) > 60 else post.content
            
            print(f"\n{i}. {content}")
            print(f"   Source: {source.platform}/@{source.username} ({source.subscriber_count:,} followers)")
            print(f"   Created: {created_str}")
            print(f"   Metrics: views={post.views:,}, likes={post.likes:,}, comments={post.comments:,}")
            if metrics:
                print(f"   Score: {metrics.normalized_score:.2f}, Engagement: {metrics.engagement_rate:.2%}")
            print(f"   URL: {post.url}")
        
        print("\n" + "=" * 80)
        
        # Show statistics
        total_posts = session.query(Post).count()
        total_sources = session.query(Source).filter_by(is_active=1).count()
        
        # Posts by date
        today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        yesterday = today - timedelta(days=1)
        week_ago = today - timedelta(days=7)
        
        posts_today = session.query(Post).filter(Post.created_at >= today).count()
        posts_yesterday = session.query(Post).filter(
            Post.created_at >= yesterday,
            Post.created_at < today
        ).count()
        posts_week = session.query(Post).filter(Post.created_at >= week_ago).count()
        
        print("STATISTICS")
        print("=" * 80)
        print(f"Total posts: {total_posts}")
        print(f"Active sources: {total_sources}")
        print(f"Posts today: {posts_today}")
        print(f"Posts yesterday: {posts_yesterday}")
        print(f"Posts this week: {posts_week}")
        print("=" * 80)
        
        print("\nNEXT STEPS:")
        print("  1. Start bot: python main.py")
        print("  2. In Telegram: /top")
        print("  3. To add more posts: python create_demo_posts.py")
        print("  4. To parse real data: python parse_and_send.py")
        print("=" * 80)
        
    except Exception as e:
        print(f"\n! ERROR: {e}")
        import traceback
        traceback.print_exc()
    finally:
        session.close()


if __name__ == "__main__":
    show_top_posts(limit=10)
