#!/usr/bin/env python3

"""Debug script to understand the trends calculation issue."""

import sys
from pathlib import Path
from datetime import datetime, timedelta
from unittest.mock import patch

# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from storm_logger.utils.business_metrics import (
    BusinessMetric,
    BusinessMetricsCollector,
    MetricType,
)

def test_trends_calculation():
    """Test the trends calculation directly."""
    collector = BusinessMetricsCollector(retention_period=timedelta(days=30))
    
    # Create realistic time series data
    base_time = datetime(2024, 1, 1, 12, 0, 0)
    
    print("Adding metrics...")
    
    with patch('storm_logger.utils.business_metrics.datetime') as mock_dt:
        # Week 1: Poor performance (declining trend)
        for day in range(7):
            mock_dt.now.return_value = base_time + timedelta(days=day)
            
            # Response time degrading
            response_time = 0.1 + (day * 0.05)  # 100ms to 400ms
            collector.add_metric("response_time", response_time, MetricType.PERFORMANCE)
            
            # Success rate declining
            success_rate = 95 - (day * 2)  # 95% to 81%
            collector.add_metric("success_rate", success_rate, MetricType.QUALITY, threshold=90)
            
            # Revenue declining
            daily_revenue = 10000 - (day * 500)  # $10k to $7k
            collector.add_metric("daily_revenue", daily_revenue, MetricType.REVENUE)
        
        # Week 2: Improvement (recovery trend)
        for day in range(7, 14):
            mock_dt.now.return_value = base_time + timedelta(days=day)
            
            # Response time improving
            response_time = 0.4 - ((day - 7) * 0.03)  # 400ms to 190ms
            collector.add_metric("response_time", response_time, MetricType.PERFORMANCE)
            
            # Success rate improving
            success_rate = 81 + ((day - 7) * 2)  # 81% to 95%
            collector.add_metric("success_rate", success_rate, MetricType.QUALITY, threshold=90)
            
            # Revenue recovering
            daily_revenue = 7000 + ((day - 7) * 300)  # $7k to $9.1k
            collector.add_metric("daily_revenue", daily_revenue, MetricType.REVENUE)
        
        # Week 3: Stable performance
        for day in range(14, 21):
            mock_dt.now.return_value = base_time + timedelta(days=day)
            
            # Stable response time with minor fluctuations
            response_time = 0.15 + (0.01 if day % 2 else -0.01)
            collector.add_metric("response_time", response_time, MetricType.PERFORMANCE)
            
            # Stable success rate
            success_rate = 96 + (1 if day % 3 == 0 else 0)
            collector.add_metric("success_rate", success_rate, MetricType.QUALITY, threshold=90)
            
            # Steady revenue growth
            daily_revenue = 9000 + ((day - 14) * 50)
            collector.add_metric("daily_revenue", daily_revenue, MetricType.REVENUE)

    print(f"Total metrics added: {len(collector._metrics)}")
    print(f"Metric summaries: {list(collector._metric_summaries.keys())}")
    
    # Set the current time for trend calculation to the last day we added metrics
    with patch('storm_logger.utils.business_metrics.datetime') as mock_dt_trends:
        mock_dt_trends.now.return_value = base_time + timedelta(days=21)
        trends = collector._calculate_trends()
    
    print(f"Calculated trends: {trends}")
    
    if "response_time" in trends:
        print("✓ response_time found in trends")
    else:
        print("✗ response_time NOT found in trends")
        print("Debugging trend calculation...")
        
        # Let's debug the trend calculation manually
        now = datetime.now()
        last_week = now - timedelta(days=7)
        prev_week = now - timedelta(days=14)
        
        print(f"Now: {now}")
        print(f"Last week: {last_week}")
        print(f"Prev week: {prev_week}")
        
        recent_metrics = [m for m in collector._metrics 
                        if m.name == "response_time" and m.timestamp >= last_week]
        previous_metrics = [m for m in collector._metrics 
                          if m.name == "response_time" and prev_week <= m.timestamp < last_week]
        
        print(f"Recent metrics count: {len(recent_metrics)}")
        print(f"Previous metrics count: {len(previous_metrics)}")
        
        if recent_metrics:
            print(f"Recent metric timestamps: {[m.timestamp for m in recent_metrics]}")
        if previous_metrics:
            print(f"Previous metric timestamps: {[m.timestamp for m in previous_metrics]}")

if __name__ == "__main__":
    test_trends_calculation()