#!/usr/bin/env python3
"""
Test script for account-specific analytics with total metrics.
"""

import sys
import os
from datetime import date, timedelta

# Add the project root to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from src.utils.db import get_db_session
from src.marketing.apps.Analytics.twitter_analytics import get_account_specific_analytics


def test_account_analytics():
    """Test account-specific analytics with total metrics."""
    print("🧪 Testing Account-Specific Analytics with Total Metrics")
    print("=" * 60)
    
    # Test parameters
    account_id = 53  # Use the account ID from your test data
    start_date = date(2025, 8, 1)
    end_date = date(2025, 8, 30)
    
    try:
        # Get database session
        db = get_db_session()
        
        print(f"📊 Testing with account_id: {account_id}")
        print(f"📅 Date range: {start_date} to {end_date}")
        print()
        
        # Test account-specific analytics
        print("🔍 Getting account-specific analytics...")
        result = get_account_specific_analytics(db, account_id, start_date, end_date)
        
        if result.get("success"):
            print("✅ Analytics retrieved successfully!")
            print()
            
            data = result.get("data", {})
            
            # Display account info
            account_info = data.get("account_info", {})
            print("📱 Account Information:")
            print(f"   ID: {account_info.get('id')}")
            print(f"   Username: {account_info.get('username')}")
            print(f"   Platform: {account_info.get('platform')}")
            print()
            
            # Display total metrics
            total_metrics = data.get("total_metrics", {})
            print("📊 Total Metrics:")
            print(f"   Total Posts: {total_metrics.get('total_posts', 0)}")
            print(f"   Total Likes: {total_metrics.get('total_likes', 0)}")
            print(f"   Total Comments: {total_metrics.get('total_comments', 0)}")
            print(f"   Total Shares: {total_metrics.get('total_shares', 0)}")
            print()
            
            # Display engagement metrics
            engagement_metrics = data.get("engagement_metrics", {})
            print("🎯 Engagement Metrics:")
            print(f"   Post Impressions: {engagement_metrics.get('post_impressions', 0)}")
            print(f"   Post Retweets: {engagement_metrics.get('post_retweets', 0)}")
            print(f"   Post Engagements: {engagement_metrics.get('post_engagements', 0)}")
            print(f"   Post Engagement Rate: {engagement_metrics.get('post_engagement_rate', 0):.4f}")
            print()
            
            # Display top tweets
            top_tweets = data.get("top_tweets", [])
            print(f"🏆 Top Tweets ({len(top_tweets)}):")
            for i, tweet in enumerate(top_tweets[:3]):
                print(f"   {i+1}. {tweet.get('content', 'No content')[:50]}...")
                print(f"      Impressions: {tweet.get('impressions', 0)}")
                print(f"      Reactions: {tweet.get('reactions', 0)}")
                print(f"      Comments: {tweet.get('comments', 0)}")
                print(f"      Shares: {tweet.get('shares', 0)}")
                print(f"      Engagement Rate: {tweet.get('engagement_rate', 0):.4f}")
                print()
            
            # Display overall engagement rates
            overall_rates = data.get("overall_engagement_rates", [])
            print("📈 Overall Engagement Rates:")
            for i, rate in enumerate(overall_rates):
                print(f"   Rate {i+1}: {rate:.4f}%")
            print()
            
            # Verify total metrics consistency
            print("🔍 Verifying Total Metrics Consistency:")
            calculated_total_posts = len(top_tweets) if top_tweets else 0
            calculated_total_likes = sum(tweet.get('reactions', 0) for tweet in top_tweets)
            calculated_total_comments = sum(tweet.get('comments', 0) for tweet in top_tweets)
            calculated_total_shares = sum(tweet.get('shares', 0) for tweet in top_tweets)
            
            print(f"   Calculated from top tweets:")
            print(f"     Total Posts: {calculated_total_posts}")
            print(f"     Total Likes: {calculated_total_likes}")
            print(f"     Total Comments: {calculated_total_comments}")
            print(f"     Total Shares: {calculated_total_shares}")
            print()
            
            print(f"   From total_metrics:")
            print(f"     Total Posts: {total_metrics.get('total_posts', 0)}")
            print(f"     Total Likes: {total_metrics.get('total_likes', 0)}")
            print(f"     Total Comments: {total_metrics.get('total_comments', 0)}")
            print(f"     Total Shares: {total_metrics.get('total_shares', 0)}")
            print()
            
        else:
            print(f"❌ Failed to retrieve analytics: {result.get('message', 'Unknown error')}")
        
        db.close()
        
    except Exception as e:
        print(f"❌ Error during testing: {str(e)}")
        import traceback
        traceback.print_exc()
        
        if 'db' in locals():
            db.close()


if __name__ == "__main__":
    print("🚀 Account-Specific Analytics Test")
    print("=" * 60)
    
    test_account_analytics()
    
    print("\n�� Test completed!")
