#!/usr/bin/env python3

"""Debug script to understand business trends 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_business_collector():
    """Test the business collector fixture logic."""
    collector = BusinessMetricsCollector()
    
    with patch('storm_logger.utils.business_metrics.datetime') as mock_dt:
        base_time = datetime(2024, 1, 1, 9, 0, 0)
        
        # Simulate realistic business day patterns over 36 hours
        for hour in range(36):
            current_time = base_time + timedelta(hours=hour)
            mock_dt.now.return_value = current_time
            
            # Business hours factor (higher activity during business hours)
            business_hour = (hour % 24) >= 9 and (hour % 24) <= 17
            business_hour_factor = 1.2 if business_hour else 0.3
            
            # Active users (follows business hours)
            active_users = int(1000 * business_hour_factor)
            collector.add_metric("active_users", active_users, MetricType.USAGE)
            
            # Transaction volume
            transactions = int(500 * business_hour_factor)
            collector.add_metric("hourly_transactions", transactions, MetricType.REVENUE)
            
            # System performance under load
            cpu_usage = min(95, 20 + (transactions / 10))
            collector.add_metric("cpu_usage", cpu_usage, MetricType.PERFORMANCE, threshold=80)
            
            # Customer satisfaction (inverse of response time)
            response_time = 0.1 + (transactions / 10000)
            satisfaction_score = max(1, 5 - (response_time * 10))
            collector.add_metric("customer_satisfaction", satisfaction_score, MetricType.CUSTOMER_SATISFACTION, threshold=4.0)
    
    print(f"Total metrics added: {len(collector._metrics)}")
    print(f"Metric summaries: {list(collector._metric_summaries.keys())}")
    
    # Test the business intelligence report with proper datetime mocking
    with patch('storm_logger.utils.business_metrics.datetime') as mock_dt:
        mock_dt.now.return_value = base_time + timedelta(hours=36)
        
        # Debug the trend calculation manually
        now = base_time + timedelta(hours=36)
        last_week = now - timedelta(days=7)
        prev_week = now - timedelta(days=14)
        
        print(f"Trend calculation timeframe:")
        print(f"  Now: {now}")
        print(f"  Last week start: {last_week}")
        print(f"  Previous week start: {prev_week}")
        print(f"  Data timeframe: {base_time} to {base_time + timedelta(hours=36)}")
        
        # Check if we have data in the expected windows
        for metric_name in collector._metric_summaries.keys():
            recent_metrics = [m for m in collector._metrics 
                            if m.name == metric_name and m.timestamp >= last_week]
            previous_metrics = [m for m in collector._metrics 
                              if m.name == metric_name and prev_week <= m.timestamp < last_week]
            
            print(f"  {metric_name}: recent={len(recent_metrics)}, previous={len(previous_metrics)}")
        
        report = collector.get_business_intelligence_report()
    
    print(f"Report keys: {list(report.keys())}")
    
    if "trends" in report:
        trends = report["trends"]
        print(f"Trends keys: {list(trends.keys())}")
        
        # Test the specific assertion
        business_metrics = ["active_users", "hourly_transactions", "customer_satisfaction"]
        trend_metrics = list(trends.keys())
        
        print(f"Looking for business metrics: {business_metrics}")
        print(f"Available trend metrics: {trend_metrics}")
        
        found_any = any(metric in trend_metrics for metric in business_metrics)
        print(f"Found any match: {found_any}")
        
        for metric in business_metrics:
            if metric in trend_metrics:
                print(f"✓ Found {metric} in trends")
            else:
                print(f"✗ Missing {metric} in trends")
    else:
        print("No trends in report")

if __name__ == "__main__":
    test_business_collector()