#!/usr/bin/env python3
"""
Demonstration script for PrecipGen Workflow Testing Infrastructure.

This script shows how to use the core testing infrastructure components:
- DirectoryManager for organized file management
- TestConfig for configuration management  
- TestLogger for structured test logging
- Property-based testing for directory organization
"""

import sys
import tempfile
from pathlib import Path

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

from tests.workflow_testing.infrastructure import DirectoryManager, TestConfig, TestLogger


def demo_directory_management():
    """Demonstrate directory management capabilities."""
    print("=== Directory Management Demo ===")
    
    with tempfile.TemporaryDirectory(prefix="precipgen_demo_") as temp_dir:
        manager = DirectoryManager(base_dir=temp_dir)
        
        # Create station directories for multiple stations
        stations = ["USC00426128", "USW00024127", "CAM00071395"]
        
        for station_id in stations:
            station_dir = manager.create_station_directory(station_id)
            print(f"Created: {station_dir}")
            
            # Create timestamped subdirectories
            for workflow in ["analysis", "simulation", "validation"]:
                timestamped_dir = manager.create_timestamped_subdirectory(station_id, workflow)
                print(f"  Timestamped {workflow}: {timestamped_dir.name}")
        
        # List all station directories
        station_list = manager.list_station_directories(base_dir=temp_dir)
        print(f"\nFound {len(station_list)} station directories:")
        
        for station in station_list:
            print(f"  {station.station_id}: {station.total_size_mb:.3f} MB")
        
        # Get output summary
        summary = manager.get_output_summary(base_dir=temp_dir)
        print(f"\nTotal stations: {summary['total_stations']}")
        print(f"Total size: {summary['total_size_mb']:.3f} MB")


def demo_configuration_management():
    """Demonstrate configuration management capabilities."""
    print("\n=== Configuration Management Demo ===")
    
    config = TestConfig()
    
    # Show basic configuration
    print(f"Base output directory: {config.get_base_output_dir()}")
    print(f"Test data directory: {config.get_test_data_dir()}")
    print(f"Parallel execution: {config.is_parallel_execution_enabled()}")
    
    # Show workflow configurations
    workflows = ["data_acquisition", "data_analysis", "simulation", "validation"]
    for workflow in workflows:
        try:
            wf_config = config.get_workflow_config(workflow)
            print(f"{workflow}: timeout={wf_config.timeout_seconds}s, threshold={wf_config.validation_threshold}")
        except KeyError:
            print(f"{workflow}: not configured")
    
    # Show gold standard configuration
    gold_config = config.get_gold_standard_config()
    print(f"Gold standard station: {gold_config['station_id']}")
    print(f"Gold standard location: {gold_config['location_name']}")
    
    # Validate configuration
    issues = config.validate_config()
    if issues:
        print(f"Configuration issues: {issues}")
    else:
        print("Configuration is valid")


def demo_test_logging():
    """Demonstrate test logging capabilities."""
    print("\n=== Test Logging Demo ===")
    
    with tempfile.TemporaryDirectory(prefix="precipgen_log_demo_") as temp_dir:
        with WorkflowTestLogger("demo_test", log_dir=temp_dir) as logger:
            logger.start_test_execution("Demonstration test execution")
            
            # Log various test results
            logger.log_test_result("test_directory_creation", True, 0.05)
            logger.log_test_result("test_file_organization", True, 0.12)
            logger.log_test_result("test_validation_logic", False, 0.08, 
                                 details={"error": "Validation threshold not met"})
            
            # Log performance metrics
            logger.log_performance_metric("memory_usage", 45.2, "MB")
            logger.log_performance_metric("execution_time", 1.25, "seconds")
            
            # Log validation results
            logger.log_validation_result("parameter_count", 48, 47, False, threshold=48)
            logger.log_validation_result("success_rate", 0.85, 0.92, True, threshold=0.85)
            
            logger.end_test_execution(True, "Demo completed successfully")
            
            # Show test summary
            print(f"Test success rate: {logger.get_success_rate():.1f}%")
            print(f"Failed tests: {len(logger.get_failed_tests())}")
            
            # Generate and save report
            report_file = logger.save_test_report()
            print(f"Test report saved to: {Path(report_file).name}")


def demo_property_based_testing():
    """Demonstrate property-based testing integration."""
    print("\n=== Property-Based Testing Demo ===")
    
    # This would normally be run via pytest, but we can show the concept
    from tests.workflow_testing.test_directory_organization import TestDirectoryOrganization
    
    print("Property-based tests validate universal properties:")
    print("1. Directory Organization Consistency")
    print("2. Custom Output Directory Handling") 
    print("3. Workflow Subdirectory Consistency")
    print("4. Multiple Station Organization")
    
    print("\nRun with: python -m pytest tests/workflow_testing/test_directory_organization.py -v")


def main():
    """Run all demonstrations."""
    print("PrecipGen Workflow Testing Infrastructure Demo")
    print("=" * 50)
    
    demo_directory_management()
    demo_configuration_management()
    demo_test_logging()
    demo_property_based_testing()
    
    print("\n" + "=" * 50)
    print("Demo completed! The testing infrastructure is ready for use.")
    print("\nNext steps:")
    print("1. Implement workflow-specific testers (Data Acquisition, Analysis, etc.)")
    print("2. Add CLI interface for running tests")
    print("3. Create Jupyter notebook examples")
    print("4. Implement performance and scalability testing")


if __name__ == "__main__":
    main()
