#!/usr/bin/env python3
"""
Test script to verify period stats consistency (daily, weekly, monthly).
This test ensures that the stats show consistent time periods regardless of trading activity.
"""

import sys
import os
import tempfile
from datetime import datetime, timedelta

# Add src directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from trading_stats import TradingStats

def test_period_stats_consistency():
    """Test that period stats show consistent time periods."""
    
    # Create temporary stats file
    with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
        temp_file = f.name
    
    try:
        # Initialize TradingStats
        stats = TradingStats(temp_file)
        stats.set_initial_balance(10000.0)
        
        print("Testing Period Stats Consistency")
        print("=" * 40)
        
        # Test Case 1: No trades - should still show 10 periods
        print("\n1. Testing with no trades:")
        daily_stats = stats.get_daily_stats(10)
        weekly_stats = stats.get_weekly_stats(10)
        monthly_stats = stats.get_monthly_stats(10)
        
        print(f"   Daily periods: {len(daily_stats)} (should be 10)")
        print(f"   Weekly periods: {len(weekly_stats)} (should be 10)")
        print(f"   Monthly periods: {len(monthly_stats)} (should be 10)")
        
        # Verify all periods have has_trades = False
        daily_no_trades = sum(1 for day in daily_stats if not day['has_trades'])
        weekly_no_trades = sum(1 for week in weekly_stats if not week['has_trades'])
        monthly_no_trades = sum(1 for month in monthly_stats if not month['has_trades'])
        
        print(f"   Days with no trades: {daily_no_trades}/10")
        print(f"   Weeks with no trades: {weekly_no_trades}/10")
        print(f"   Months with no trades: {monthly_no_trades}/10")
        
        # Test Case 2: Add some trades on specific days
        print("\n2. Testing with selective trades:")
        
        # Add trade today
        today = datetime.now()
        stats.record_trade_with_enhanced_tracking("BTC/USDC", "buy", 0.1, 50000.0, "test1")
        stats.record_trade_with_enhanced_tracking("BTC/USDC", "sell", 0.1, 51000.0, "test2")
        
        # Add trade 3 days ago
        three_days_ago = today - timedelta(days=3)
        stats.record_trade_with_enhanced_tracking("ETH/USDC", "buy", 1.0, 3000.0, "test3")
        stats.record_trade_with_enhanced_tracking("ETH/USDC", "sell", 1.0, 3100.0, "test4")
        
        # Get updated stats
        daily_stats = stats.get_daily_stats(10)
        weekly_stats = stats.get_weekly_stats(10)
        monthly_stats = stats.get_monthly_stats(10)
        
        print(f"   Daily periods: {len(daily_stats)} (should still be 10)")
        print(f"   Weekly periods: {len(weekly_stats)} (should still be 10)")
        print(f"   Monthly periods: {len(monthly_stats)} (should still be 10)")
        
        # Count periods with trades
        daily_with_trades = sum(1 for day in daily_stats if day['has_trades'])
        weekly_with_trades = sum(1 for week in weekly_stats if week['has_trades'])
        monthly_with_trades = sum(1 for month in monthly_stats if month['has_trades'])
        
        print(f"   Days with trades: {daily_with_trades} (should be 2)")
        print(f"   Weeks with trades: {weekly_with_trades}")
        print(f"   Months with trades: {monthly_with_trades}")
        
        # Test Case 3: Check date consistency
        print("\n3. Testing date consistency:")
        today_str = datetime.now().strftime('%Y-%m-%d')
        
        # Today should be the first entry (index 0)
        if daily_stats[0]['date'] == today_str:
            print(f"   ✅ Today ({today_str}) is first in daily stats")
        else:
            print(f"   ❌ Today mismatch: expected {today_str}, got {daily_stats[0]['date']}")
        
        # Check that dates are consecutive going backwards
        dates_correct = True
        for i in range(1, len(daily_stats)):
            expected_date = (datetime.now().date() - timedelta(days=i)).strftime('%Y-%m-%d')
            if daily_stats[i]['date'] != expected_date:
                dates_correct = False
                print(f"   ❌ Date mismatch at index {i}: expected {expected_date}, got {daily_stats[i]['date']}")
                break
        
        if dates_correct:
            print(f"   ✅ All daily dates are consecutive and correct")
        
        # Test Case 4: Verify P&L calculations only for trading periods
        print("\n4. Testing P&L calculations:")
        total_pnl = 0
        trading_days = 0
        
        for day in daily_stats:
            if day['has_trades']:
                total_pnl += day['pnl']
                trading_days += 1
                print(f"   Trading day {day['date_formatted']}: P&L ${day['pnl']:.2f}")
            else:
                # Should have zero P&L and zero trades
                if day['pnl'] == 0 and day['trades'] == 0:
                    print(f"   No-trade day {day['date_formatted']}: ✅ Correctly shows $0.00")
                else:
                    print(f"   No-trade day {day['date_formatted']}: ❌ Should show $0.00")
        
        print(f"   Total P&L from trading days: ${total_pnl:.2f}")
        print(f"   Trading days count: {trading_days}")
        
        print("\n✅ Period stats consistency test completed!")
        print("📊 All periods now show consistent time ranges")
        print("🎯 Days/weeks/months with no trades are properly displayed")
        return True
        
    except Exception as e:
        print(f"❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    finally:
        # Clean up temp file
        if os.path.exists(temp_file):
            os.unlink(temp_file)

if __name__ == "__main__":
    success = test_period_stats_consistency()
    exit(0 if success else 1)