#!/usr/bin/env python3
"""
Challenge Window Analysis Tool
Analyzes optimal challenge window duration
"""

import json
import sys
from typing import Dict, List
from dataclasses import dataclass

@dataclass
class ChallengeWindowAnalysis:
    """Challenge window analysis result"""
    window_duration: int  # seconds
    avg_block_time: float
    blocks_in_window: float
    fraud_detection_time: float
    user_experience_impact: str
    recommendation: str

def analyze_challenge_window(
    window_durations: List[int],  # seconds
    avg_block_time: float = 12.0,  # Ethereum average block time
    fraud_detection_time: float = 300.0,  # 5 minutes average
    user_tolerance: float = 3600.0  # 1 hour user tolerance
) -> List[ChallengeWindowAnalysis]:
    """
    Analyze challenge window durations
    
    Args:
        window_durations: List of window durations in seconds
        avg_block_time: Average block time in seconds
        fraud_detection_time: Average time to detect fraud
        user_tolerance: Maximum acceptable delay for users
    
    Returns:
        List of analysis results
    """
    results = []
    
    for window in window_durations:
        blocks_in_window = window / avg_block_time
        
        # User experience impact
        if window < 300:  # 5 minutes
            ux_impact = "Excellent - very fast"
        elif window < 1800:  # 30 minutes
            ux_impact = "Good - acceptable"
        elif window < 3600:  # 1 hour
            ux_impact = "Fair - noticeable delay"
        else:
            ux_impact = "Poor - significant delay"
        
        # Recommendation
        if window < fraud_detection_time:
            recommendation = f"Window too short - increase to at least {fraud_detection_time} seconds"
        elif window > user_tolerance:
            recommendation = f"Window too long - decrease to improve UX"
        elif fraud_detection_time <= window <= user_tolerance:
            recommendation = "Window is optimal"
        else:
            recommendation = "Consider adjusting window duration"
        
        results.append(ChallengeWindowAnalysis(
            window_duration=window,
            avg_block_time=avg_block_time,
            blocks_in_window=blocks_in_window,
            fraud_detection_time=fraud_detection_time,
            user_experience_impact=ux_impact,
            recommendation=recommendation
        ))
    
    return results

def print_analysis(results: List[ChallengeWindowAnalysis]):
    """Print challenge window analysis results"""
    print("=" * 100)
    print("Challenge Window Analysis")
    print("=" * 100)
    print(f"{'Duration':<12} {'Blocks':<10} {'UX Impact':<25} {'Recommendation':<40}")
    print("-" * 100)
    
    for result in results:
        duration_str = f"{result.window_duration}s ({result.window_duration/60:.1f}m)"
        print(f"{duration_str:<12} "
              f"{result.blocks_in_window:>8.1f}  "
              f"{result.user_experience_impact:<25} "
              f"{result.recommendation:<40}")
    
    print("=" * 100)

def main():
    """Main entry point"""
    # Example window durations to analyze (in seconds)
    window_durations = [60, 300, 600, 1800, 3600, 7200]  # 1min, 5min, 10min, 30min, 1h, 2h
    
    # Analyze challenge windows
    results = analyze_challenge_window(window_durations)
    
    # Print results
    print_analysis(results)
    
    # Optional: Export to JSON
    if len(sys.argv) > 1 and sys.argv[1] == '--json':
        output = {
            'analysis': [
                {
                    'window_duration': r.window_duration,
                    'blocks_in_window': r.blocks_in_window,
                    'user_experience_impact': r.user_experience_impact,
                    'recommendation': r.recommendation
                }
                for r in results
            ]
        }
        print(json.dumps(output, indent=2))

if __name__ == '__main__':
    main()

