"""Проверка есть ли PostMetrics у постов за вчера"""

from src.database.db import get_session
from src.database.models import Post, PostMetrics, Source
from src.utils.time_window import get_time_window


def check():
    session = get_session()
    
    try:
        start, end = get_time_window('yesterday')
        
        # Все посты за вчера от zillow
        posts = session.query(Post).join(Source).filter(
            Source.username == 'zillow',
            Post.created_at >= start,
            Post.created_at < end
        ).all()
        
        print("=" * 60)
        print(f"POSTS FROM YESTERDAY (zillow)")
        print("=" * 60)
        print(f"Filter: {start} to {end}")
        print(f"Found: {len(posts)} posts")
        print()
        
        for p in posts:
            metrics = session.query(PostMetrics).filter_by(post_id=p.id).first()
            has_metrics = metrics is not None
            
            print(f"Post: {p.external_id}")
            print(f"  Created: {p.created_at}")
            print(f"  Has PostMetrics: {has_metrics}")
            if metrics:
                print(f"  Score: {metrics.normalized_score:.2f}")
            print()
        
        # Проверить запрос как в handlers.py
        print("=" * 60)
        print("QUERY LIKE IN handlers.py")
        print("=" * 60)
        
        from sqlalchemy.orm import joinedload
        from sqlalchemy import func, and_
        
        all_instagram_posts = session.query(Post).outerjoin(
            PostMetrics, Post.id == PostMetrics.post_id
        ).join(
            Source, Post.source_id == Source.id
        ).options(
            joinedload(Post.source),
            joinedload(Post.metrics)
        ).filter(
            and_(Post.created_at >= start, Post.created_at < end),
            Source.platform == 'instagram'
        ).order_by(
            func.coalesce(PostMetrics.normalized_score, 0).desc(),
            Post.views.desc(),
            Post.likes.desc()
        ).limit(50).all()
        
        print(f"Query returned: {len(all_instagram_posts)} posts")
        
        for p in all_instagram_posts[:5]:
            print(f"  - {p.source.username}: {p.external_id} (score: {p.metrics.normalized_score if p.metrics else 0:.2f})")
        
    finally:
        session.close()


if __name__ == "__main__":
    check()
