"""
Скрипт для проверки и исправления метрик в базе данных
Проверяет, что метрики правильно сохранены и отображаются
"""

import sys
import os
from dotenv import load_dotenv

# Fix encoding for Windows
if sys.platform == 'win32':
    os.environ['PYTHONIOENCODING'] = 'utf-8'
    if hasattr(sys.stdout, 'reconfigure'):
        sys.stdout.reconfigure(encoding='utf-8')
        sys.stderr.reconfigure(encoding='utf-8')

load_dotenv()

from src.database.db import get_session
from src.database.models import Post, PostMetrics, Source
from sqlalchemy.orm import joinedload

def check_metrics():
    """Проверить метрики в базе данных"""
    session = get_session()
    try:
        # Get all posts with metrics
        posts = session.query(Post).options(
            joinedload(Post.metrics),
            joinedload(Post.source)
        ).limit(20).all()
        
        print("=" * 60)
        print("ПРОВЕРКА МЕТРИК В БАЗЕ ДАННЫХ")
        print("=" * 60)
        print(f"Всего постов проверено: {len(posts)}\n")
        
        posts_with_metrics = 0
        posts_with_zero_metrics = 0
        posts_without_metrics = 0
        
        for i, post in enumerate(posts, 1):
            print(f"\nПост #{i}:")
            print(f"  ID: {post.id}")
            print(f"  External ID: {post.external_id}")
            print(f"  Источник: {post.source.platform}/@{post.source.username}")
            print(f"  URL: {post.url}")
            print(f"  Содержание: {post.content[:100] if post.content else 'Нет'}...")
            print(f"  Метрики из Post:")
            print(f"    👁 Просмотры: {post.views:,}")
            print(f"    ❤️ Лайки: {post.likes:,}")
            print(f"    💬 Комментарии: {post.comments:,}")
            print(f"    🔄 Репосты: {post.shares:,}")
            print(f"    ⚡ Реакции: {post.reactions:,}")
            
            if post.metrics:
                posts_with_metrics += 1
                print(f"  Метрики из PostMetrics:")
                print(f"    📈 Engagement Rate: {post.metrics.engagement_rate:.2f}%")
                print(f"    ⭐️ Normalized Score: {post.metrics.normalized_score:.2f}")
                print(f"    📊 Total Engagement: {post.metrics.total_engagement:,}")
                
                if post.views == 0 and post.likes == 0 and post.comments == 0:
                    posts_with_zero_metrics += 1
                    print(f"    ⚠️ ВНИМАНИЕ: Все метрики равны 0!")
            else:
                posts_without_metrics += 1
                print(f"  ⚠️ ВНИМАНИЕ: Нет PostMetrics!")
        
        print("\n" + "=" * 60)
        print("СТАТИСТИКА:")
        print(f"  Постов с метриками: {posts_with_metrics}")
        print(f"  Постов без метрик: {posts_without_metrics}")
        print(f"  Постов с нулевыми метриками: {posts_with_zero_metrics}")
        print("=" * 60)
        
    except Exception as e:
        print(f"Ошибка: {e}")
        import traceback
        traceback.print_exc()
    finally:
        session.close()

if __name__ == '__main__':
    check_metrics()

