"""
Functional tests for Standalone Python examples in QUICKSTART.md.

This test module validates that all standalone Python examples from the QUICKSTART guide
work correctly and provide a good user experience.
"""

import os
import sys
import time
import tempfile
import multiprocessing
import queue
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock, call
import pytest

# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from storm_logger.integrations.standalone import (
    get_standalone_logger,
    setup_script_logging,
    setup_cli_logging,
    configure_standalone_logging,
    ScriptProgressLogger,
    detect_standalone_context,
)
from storm_logger.config import StormLoggerConfig, LogLevel


class TestQuickStartStandaloneExamples:
    """Test all Standalone Python examples from QUICKSTART.md."""
    
    # ==================== Quick Setup (15 seconds) ====================
    
    def test_basic_setup_oneliner(self):
        """Test the one-liner basic setup from QUICKSTART.md lines 462-467."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import get_standalone_logger
        
        logger = get_standalone_logger(__name__)
        logger.info("Storm Logger is ready!")
        
        # Should work without errors
        assert logger is not None
        assert logger.name == __name__
    
    def test_quick_script_setup(self):
        """Test quick script setup from QUICKSTART.md lines 470-476."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import setup_script_logging
        
        # Perfect for data processing scripts
        logger = setup_script_logging("data_processor.py", log_level="INFO")
        logger.info("Script started")
        
        # Should work and return a logger
        assert logger is not None
        assert logger.name == "data_processor.py"
    
    def test_quick_cli_setup(self):
        """Test quick CLI setup from QUICKSTART.md lines 479-485."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import setup_cli_logging
        
        # Perfect for command-line tools
        logger = setup_cli_logging("myapp", verbosity=1, quiet=False)
        logger.info("CLI application ready")
        
        # Should work and return a logger
        assert logger is not None
        assert logger.name == "myapp"
    
    # ==================== Script Logging ====================
    
    def test_data_processing_scripts(self):
        """Test data processing scripts from QUICKSTART.md lines 490-518."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import setup_script_logging, ScriptProgressLogger
        
        # Setup logging for the script
        logger = setup_script_logging(
            script_name="data_import.py",
            log_level="INFO",
            log_to_file=True
        )
        
        # Mock functions for the example
        def load_customer_data():
            return [Mock(id=i) for i in range(5)]
        
        def process_record(record):
            pass
        
        # Track script progress
        progress = ScriptProgressLogger("data_import")
        progress.start("Processing customer data")
        
        try:
            # Your data processing logic
            records = load_customer_data()
            
            for i, record in enumerate(records):
                progress.update(i + 1, len(records), f"Processing {record.id}")
                process_record(record)
            
            progress.complete(f"Successfully processed {len(records)} records")
            
        except Exception as e:
            logger.error("Script failed", exc_info=True)
            progress.complete("Script failed with errors")
            raise
        
        # Execute the example (without the try/except to test success path)
        records = load_customer_data()
        for i, record in enumerate(records):
            progress.update(i + 1, len(records), f"Processing {record.id}")
            process_record(record)
        progress.complete(f"Successfully processed {len(records)} records")
        
        # Should complete without errors
        assert True
    
    def test_etl_data_pipeline_scripts(self):
        """Test ETL & data pipeline scripts from QUICKSTART.md lines 521-556."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import get_standalone_logger
        from storm_logger.config import StormLoggerConfig, LogLevel
        
        # Configure for ETL workloads
        with tempfile.TemporaryDirectory() as tmpdir:
            config = StormLoggerConfig(
                log_level=LogLevel.INFO,
                log_directory=tmpdir,
                enable_file_logging=True,
                enable_console=True,
                max_file_size=50 * 1024 * 1024,  # 50MB files
                backup_count=10,
            )
            
            logger = get_standalone_logger("etl_pipeline", config)
            
            # Mock ETL functions
            def extract_from_source():
                return [{"id": i, "value": i * 10} for i in range(100)]
            
            def transform_data(data):
                return [{"id": d["id"], "value": d["value"] * 2} for d in data]
            
            def load_to_destination(data):
                pass
            
            def etl_process():
                logger.info("Starting ETL pipeline")
                
                # Extract
                data = extract_from_source()
                logger.business_metric("records_extracted", len(data))
                
                # Transform
                transformed = transform_data(data)
                logger.business_metric("records_transformed", len(transformed))
                
                # Load
                load_to_destination(transformed)
                logger.business_metric("records_loaded", len(transformed))
                
                logger.success("ETL pipeline completed successfully")
            
            # Execute ETL process
            etl_process()
            
            # Should complete without errors
            assert True
    
    def test_batch_job_scripts(self):
        """Test batch job scripts from QUICKSTART.md lines 559-592."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import setup_script_logging
        
        logger = setup_script_logging(
            "batch_job.py",
            log_level="DEBUG",
            log_to_file=True
        )
        
        # Mock batch functions
        batch_counter = 0
        def get_next_batch(size):
            nonlocal batch_counter
            if batch_counter < 3:  # Return 3 batches
                batch_counter += 1
                return [{"item": i} for i in range(size)]
            return None
        
        def process_batch_items(batch):
            pass
        
        def process_batch():
            logger.info("Batch job started")
            
            try:
                # Process in batches
                batch_size = 1000
                total_processed = 0
                
                while True:
                    batch = get_next_batch(batch_size)
                    if not batch:
                        break
                    
                    logger.debug(f"Processing batch of {len(batch)} items")
                    process_batch_items(batch)
                    
                    total_processed += len(batch)
                    logger.info(f"Processed {total_processed} items so far")
                
                logger.success(f"Batch job completed. Total processed: {total_processed}")
                
            except Exception as e:
                logger.error("Batch job failed", exc_info=True)
                raise
        
        # Execute batch job
        process_batch()
        
        # Should complete without errors
        assert True
    
    # ==================== CLI Application Logging ====================
    
    def test_basic_cli_setup_with_argparse(self):
        """Test basic CLI setup from QUICKSTART.md lines 597-637."""
        # From QUICKSTART.md:
        import argparse
        from storm_logger.integrations.standalone import setup_cli_logging
        
        def create_parser():
            parser = argparse.ArgumentParser(description="My CLI App")
            
            # Add verbosity controls
            parser.add_argument('-v', '--verbose', action='count', default=0,
                               help='Increase verbosity (-v, -vv, -vvv)')
            parser.add_argument('-q', '--quiet', action='store_true',
                               help='Suppress non-error output')
            
            return parser
        
        def main():
            parser = create_parser()
            # Simulate command line args
            args = parser.parse_args(['-v'])  # One level of verbosity
            
            # Setup logging based on CLI arguments
            logger = setup_cli_logging(
                app_name="myapp",
                verbosity=args.verbose,
                quiet=args.quiet
            )
            
            logger.info("CLI application started")
            
            # Your application logic here
            try:
                run_application(args)
                logger.success("Operation completed successfully")
            except Exception as e:
                logger.error("Operation failed", exc_info=True)
                return 1
            
            return 0
        
        def run_application(args):
            # Simulated application logic
            pass
        
        # Execute main function
        result = main()
        assert result == 0
    
    def test_advanced_cli_with_subcommands(self):
        """Test advanced CLI with subcommands from QUICKSTART.md lines 640-721."""
        # From QUICKSTART.md:
        import argparse
        from storm_logger.integrations.standalone import get_standalone_logger
        from storm_logger.config import StormLoggerConfig, LogLevel
        
        with tempfile.TemporaryDirectory() as tmpdir:
            def setup_logging(args):
                """Configure logging based on CLI arguments."""
                # Determine log level
                if args.quiet:
                    level = LogLevel.ERROR
                elif args.verbose >= 2:
                    level = LogLevel.DEBUG
                elif args.verbose == 1:
                    level = LogLevel.INFO
                else:
                    level = LogLevel.WARNING
                
                config = StormLoggerConfig(
                    log_level=level,
                    enable_console=not args.quiet,
                    enable_file_logging=args.verbose > 0,
                    console_colors=not args.no_color,
                    log_directory=tmpdir if args.verbose > 0 else None,
                )
                
                return get_standalone_logger("myapp", config)
            
            def cmd_deploy(args, logger):
                """Deploy command implementation."""
                logger.info("Starting deployment")
                
                # Deployment logic
                logger.info("Uploading files...")
                logger.info("Configuring services...")
                logger.info("Starting services...")
                
                logger.success("Deployment completed")
            
            def cmd_status(args, logger):
                """Status command implementation."""
                logger.info("Checking application status")
                
                # Check various components
                services = ["web", "api", "worker", "database"]
                for service in services:
                    try:
                        status = check_service_status(service)
                        logger.info(f"{service}: {status}")
                    except Exception as e:
                        logger.error(f"{service}: FAILED - {e}")
            
            def check_service_status(service):
                # Mock service check
                return "OK"
            
            # Create parser
            parser = argparse.ArgumentParser(description="MyApp CLI")
            
            # Global options
            parser.add_argument('-v', '--verbose', action='count', default=0)
            parser.add_argument('-q', '--quiet', action='store_true')
            parser.add_argument('--no-color', action='store_true')
            
            subparsers = parser.add_subparsers(dest='command', help='Commands')
            
            # Deploy command
            deploy_parser = subparsers.add_parser('deploy', help='Deploy application')
            deploy_parser.add_argument('--env', required=True, choices=['dev', 'staging', 'prod'])
            
            # Status command
            status_parser = subparsers.add_parser('status', help='Check status')
            
            # Simulate command execution - no verbosity so no file logging  
            args = parser.parse_args(['deploy', '--env', 'dev'])
            logger = setup_logging(args)
            
            if args.command == 'deploy':
                cmd_deploy(args, logger)
            elif args.command == 'status':
                cmd_status(args, logger)
            
            # Should complete without errors
            assert True
    
    # ==================== Service & Daemon Logging ====================
    
    def test_long_running_service(self):
        """Test long-running service from QUICKSTART.md lines 726-826."""
        # From QUICKSTART.md:
        import signal
        import time
        from storm_logger.integrations.standalone import get_standalone_logger
        from storm_logger.config import StormLoggerConfig, LogLevel
        
        with tempfile.TemporaryDirectory() as tmpdir:
            class MyService:
                def __init__(self):
                    # Configure for production service
                    config = StormLoggerConfig(
                        log_level=LogLevel.INFO,
                        log_directory=tmpdir,
                        enable_file_logging=True,
                        enable_console=False,  # No console output for daemon
                        production_mode=True,
                        max_file_size=100 * 1024 * 1024,  # 100MB
                        backup_count=5,
                    )
                    
                    self.logger = get_standalone_logger("myservice", config)
                    self.running = False
                    
                    # Setup signal handlers
                    signal.signal(signal.SIGTERM, self._handle_shutdown)
                    signal.signal(signal.SIGINT, self._handle_shutdown)
            
                def _handle_shutdown(self, signum, frame):
                    """Handle graceful shutdown."""
                    self.logger.info(f"Received signal {signum}, shutting down gracefully...")
                    self.running = False
                
                def start(self):
                    """Start the service."""
                    self.logger.info("Service starting up")
                    self.running = True
                
                    try:
                        self._main_loop()
                    except Exception as e:
                        self.logger.error("Service crashed", exc_info=True)
                        raise
                    finally:
                        self.logger.info("Service shutdown complete")
                
                def _main_loop(self):
                    """Main service loop."""
                    # Simplified for testing - run only once
                    if self.running:
                        try:
                            # Service work
                            self._process_tasks()
                            self.logger.debug("Task processing cycle completed")
                            
                            # Health check
                            if self._health_check():
                                self.logger.debug("Health check passed")
                            else:
                                self.logger.warning("Health check failed")
                            
                        except KeyboardInterrupt:
                            pass
                        except Exception as e:
                            self.logger.error("Error in main loop", exc_info=True)
                
                def _process_tasks(self):
                    """Process pending tasks."""
                    tasks = get_pending_tasks()
                    for task in tasks:
                        self.logger.info(f"Processing task {task.id}")
                        
                        try:
                            process_task(task)
                            
                            self.logger.info(f"Task {task.id} completed successfully")
                            self.logger.business_metric("tasks_completed", 1)
                            
                        except Exception as e:
                            self.logger.error(f"Task {task.id} failed", exc_info=True)
                            self.logger.business_metric("tasks_failed", 1)
                
                def _health_check(self):
                    """Perform health check."""
                    try:
                        # Check database connection
                        check_database()
                        
                        # Check external APIs
                        check_external_services()
                        
                        return True
                    except Exception as e:
                        self.logger.error("Health check failed", exc_info=True)
                        return False
        
        # Mock functions
        def get_pending_tasks():
            task = Mock()
            task.id = "task-001"
            task.type = "process"
            return [task]
        
        def process_task(task):
            pass
        
        def check_database():
            pass
        
        def check_external_services():
            pass
            
            # Create and test service (simplified)
            service = MyService()
            # Don't actually start the full service loop in test
            service._process_tasks()
            service._health_check()
            
            # Should complete without errors
            assert True
    
    @pytest.mark.skip(reason="Multiprocessing test can be flaky in CI")
    def test_worker_process(self):
        """Test worker process from QUICKSTART.md lines 829-915."""
        # This test is marked as skip because multiprocessing can be problematic in tests
        # The code is still here to validate the example syntax
        
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import get_standalone_logger
        from storm_logger.config import StormLoggerConfig, LogLevel
        import multiprocessing
        import queue
        
        def worker_process(worker_id, task_queue, config_dict):
            """Worker process function."""
            # Recreate config from dict (can't pickle StormLoggerConfig)
            config = StormLoggerConfig(**config_dict)
            logger = get_standalone_logger(f"worker_{worker_id}", config)
            
            logger.info(f"Worker {worker_id} started")
            
            while True:
                try:
                    # Get task from queue
                    task = task_queue.get(timeout=1)
                    if task is None:  # Shutdown signal
                        break
                    
                    logger.info(f"Worker {worker_id} processing task {task['id']}")
                    
                    # Process the task
                    result = process_task(task)
                    
                    logger.info(f"Worker {worker_id} completed task {task['id']}")
                    logger.business_metric("tasks_processed", 1)
                    
                except queue.Empty:
                    logger.debug(f"Worker {worker_id} waiting for tasks...")
                    break  # Exit for test
                except Exception as e:
                    logger.error(f"Worker {worker_id} error", exc_info=True)
            
            logger.info(f"Worker {worker_id} shutting down")
        
        def process_task(task):
            return {"result": "processed"}
        
        # Validate the code compiles
        assert True
    
    # ==================== Advanced Configuration ====================
    
    def test_complete_configuration_example(self):
        """Test complete configuration from QUICKSTART.md lines 920-956."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import get_standalone_logger, configure_standalone_logging
        from storm_logger.config import StormLoggerConfig, LogLevel
        
        # Create comprehensive configuration
        with tempfile.TemporaryDirectory() as tmpdir:
            config = StormLoggerConfig(
                # Core settings
                log_level=LogLevel.INFO,
                log_directory=tmpdir,
                enable_console=True,
                enable_file_logging=True,
                console_colors=True,
            
            # File settings
            max_file_size=50 * 1024 * 1024,  # 50MB
            backup_count=10,
            
            # Production settings
            production_mode=True,
            debug_mode=False,
            
            # Business intelligence
            enable_business_metrics=True,
            
            # Security
            sanitize_logs=True,
            detect_pii=True,
            )
            
            # Apply configuration globally
            configure_standalone_logging(config)
            
            # Get logger instance
            logger = get_standalone_logger(__name__)
            
            # Should work without errors
            assert logger is not None
            assert config.log_level == LogLevel.INFO
            assert config.max_file_size == 50 * 1024 * 1024
    
    def test_environment_based_configuration(self):
        """Test environment-based configuration from QUICKSTART.md lines 959-999."""
        # From QUICKSTART.md:
        import os
        from storm_logger.integrations.standalone import configure_standalone_logging
        from storm_logger.config import StormLoggerConfig, LogLevel
        
        def get_config_for_environment():
            """Get configuration based on environment."""
            env = os.getenv("APP_ENV", "development")
            
            if env == "production":
                return StormLoggerConfig(
                    log_level=LogLevel.WARNING,
                    log_directory=str(Path.home() / ".storm_logger" / "myapp"),
                    enable_console=False,
                    enable_file_logging=True,
                    production_mode=True,
                    max_file_size=100 * 1024 * 1024,
                    backup_count=5,
                )
            
            elif env == "staging":
                return StormLoggerConfig(
                    log_level=LogLevel.INFO,
                    log_directory=str(Path.home() / ".storm_logger" / "myapp"),
                    enable_console=True,
                    enable_file_logging=True,
                    production_mode=True,
                )
            
            else:  # development
                return StormLoggerConfig(
                    log_level=LogLevel.DEBUG,
                    enable_console=True,
                    enable_file_logging=False,
                    console_colors=True,
                    debug_mode=True,
                )
        
        # Configure based on environment
        config = get_config_for_environment()
        configure_standalone_logging(config)
        
        # Should return appropriate config for environment
        assert isinstance(config, StormLoggerConfig)
        # In test environment, should get development config
        assert config.debug_mode is True or config.log_level == LogLevel.DEBUG
    
    # ==================== Utility Functions ====================
    
    def test_setup_functions(self):
        """Test setup functions from QUICKSTART.md lines 1005-1028."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import (
            setup_script_logging,
            setup_cli_logging,
            get_standalone_logger
        )
        
        # Quick script setup
        logger = setup_script_logging(
            script_name="my_script.py",
            log_level="INFO",
            log_to_file=True
        )
        
        # CLI application setup
        logger = setup_cli_logging(
            app_name="myapp",
            verbosity=2,  # -vv level
            quiet=False
        )
        
        # Custom logger
        logger = get_standalone_logger("custom_component")
        
        # All setup methods should work
        assert logger is not None
    
    def test_context_detection(self):
        """Test context detection from QUICKSTART.md lines 1031-1049."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import detect_standalone_context
        import inspect
        
        def my_function():
            # Automatic context detection
            frame = inspect.currentframe()
            if frame is not None:
                context = detect_standalone_context(inspect.getframeinfo(frame))
                print(f"Current context: {context}")  # e.g., "app.main"
                return context
            return "app.general"
        
        # Context patterns recognized:
        # - app.main (main.py, main functions)
        # - app.service (service.py, Service classes)
        # - app.worker (worker.py, Worker classes)
        # - app.cli (cli.py, CLI commands)
        # - app.etl (etl.py, data processing)
        # - app.batch (batch.py, batch jobs)
        # - app.script (script.py, general scripts)
        
        context = my_function()
        assert context is not None
        assert isinstance(context, str)
        assert context.startswith("app.")
    
    # ==================== Progress Tracking ====================
    
    def test_script_progress_logger(self):
        """Test ScriptProgressLogger from QUICKSTART.md lines 1054-1078."""
        # From QUICKSTART.md:
        from storm_logger.integrations.standalone import ScriptProgressLogger
        
        # Initialize progress tracker
        progress = ScriptProgressLogger("data_migration")
        
        # Mock functions
        def get_all_users():
            users = []
            for i in range(10):
                user = Mock()
                user.username = f"user_{i}"
                users.append(user)
            return users
        
        def migrate_user(user):
            pass
        
        # Start an operation
        progress.start("Migrating user data")
        
        # Update progress
        users = get_all_users()
        for i, user in enumerate(users):
            progress.update(i + 1, len(users), f"Migrating user {user.username}")
            migrate_user(user)
        
        # Complete the operation
        progress.complete(f"Successfully migrated {len(users)} users")
        
        # Execute the example
        users = get_all_users()
        for i, user in enumerate(users):
            progress.update(i + 1, len(users), f"Migrating user {user.username}")
            migrate_user(user)
        progress.complete(f"Successfully migrated {len(users)} users")
        
        # Should complete without errors
        assert True
    
    def test_manual_progress_tracking(self):
        """Test manual progress tracking from QUICKSTART.md lines 1081-1114."""
        # From QUICKSTART.md:
        import time
        from storm_logger.integrations.standalone import get_standalone_logger
        
        logger = get_standalone_logger("data_processor")
        
        def process_large_dataset():
            logger.info("Starting large dataset processing")
            start_time = time.time()
            
            items = load_dataset()
            total_items = len(items)
            processed = 0
            
            for i, item in enumerate(items):
                # Process item
                process_item(item)
                processed += 1
                
                # Log progress every 100 items
                if processed % 100 == 0:
                    percentage = (processed / total_items) * 100
                    elapsed = time.time() - start_time
                    rate = processed / elapsed
                    eta = (total_items - processed) / rate if rate > 0 else 0
                    
                    logger.info(
                        f"Progress: {percentage:.1f}% ({processed}/{total_items}) "
                        f"Rate: {rate:.1f} items/sec, ETA: {eta:.0f}s"
                    )
            
            duration = time.time() - start_time
            logger.success(f"Processing completed in {duration:.2f}s")
        
        # Mock functions
        def load_dataset():
            return [{"id": i} for i in range(300)]
        
        def process_item(item):
            pass
        
        # Execute the function
        process_large_dataset()
        
        # Should complete without errors
        assert True
    
    # ==================== Production Deployment ====================
    
    def test_production_configuration(self):
        """Test production configuration from QUICKSTART.md lines 1120-1159."""
        # From QUICKSTART.md:
        # production_config.py
        from storm_logger.integrations.standalone import configure_standalone_logging
        from storm_logger.config import StormLoggerConfig, LogLevel
        import os
        
        def setup_production_logging():
            """Setup production-ready logging configuration."""
            config = StormLoggerConfig(
                # Production log level
                log_level=LogLevel.WARNING,
                
                # Log to dedicated directory
                log_directory=str(Path.home() / ".storm_logger" / "myapp"),
                
                # Disable console output for daemons
                enable_console=False,
                enable_file_logging=True,
                
                # Production mode features
                production_mode=True,
                
                # Log rotation
                max_file_size=100 * 1024 * 1024,  # 100MB
                backup_count=10,
                
                # Business metrics for monitoring
                enable_business_metrics=True,
                
                # Security
                sanitize_logs=True,
                detect_pii=True,
            )
            
            configure_standalone_logging(config)
            return config
        
        # Test the configuration
        config = setup_production_logging()
        
        # Verify production settings
        assert config.log_level == LogLevel.WARNING
        assert config.enable_console is False
        assert config.enable_file_logging is True
        assert config.production_mode is True
        assert config.sanitize_logs is True
    
    def test_monitoring_integration(self):
        """Test monitoring integration from QUICKSTART.md lines 1240-1280."""
        # From QUICKSTART.md:
        # monitoring.py
        from storm_logger.integrations.standalone import get_standalone_logger
        # import psutil  # Skipping actual psutil for test
        import time
        
        class SystemMonitor:
            def __init__(self):
                self.logger = get_standalone_logger("system_monitor")
            
            def monitor_system(self):
                """Monitor system resources and log metrics."""
                # Simplified for testing - just log once
                # CPU usage
                cpu_percent = 45.5  # Mock value
                self.logger.business_metric("cpu_usage_percent", cpu_percent)
                
                # Memory usage
                memory_percent = 62.3  # Mock value
                memory_available_gb = 8.5  # Mock value
                self.logger.business_metric("memory_usage_percent", memory_percent)
                self.logger.business_metric("memory_available_gb", memory_available_gb)
                
                # Disk usage
                disk_usage_percent = 75.2  # Mock value
                self.logger.business_metric("disk_usage_percent", disk_usage_percent)
                
                # Network I/O
                network_bytes_sent = 1024000  # Mock value
                network_bytes_recv = 2048000  # Mock value
                self.logger.business_metric("network_bytes_sent", network_bytes_sent)
                self.logger.business_metric("network_bytes_recv", network_bytes_recv)
                
                # Log summary
                if cpu_percent > 80 or memory_percent > 80:
                    self.logger.warning(f"High resource usage: CPU={cpu_percent}%, Memory={memory_percent}%")
        
        # Test monitor
        monitor = SystemMonitor()
        monitor.monitor_system()
        
        # Should complete without errors
        assert True


class TestStandaloneCodeUsageExamples:
    """Test actual code usage examples from the Standalone section."""
    
    def test_import_paths(self):
        """Test import paths from QUICKSTART.md lines 1319-1328."""
        # From QUICKSTART.md:
        # Import paths for standalone
        from storm_logger.integrations.standalone import (
            get_standalone_logger,           # Get standalone logger
            setup_script_logging,            # Quick script setup
            setup_cli_logging,               # CLI application setup
            configure_standalone_logging,    # Global configuration
            ScriptProgressLogger,            # Progress tracking
            detect_standalone_context,       # Context detection
        )
        
        # All imports should work
        assert get_standalone_logger is not None
        assert setup_script_logging is not None
        assert setup_cli_logging is not None
        assert configure_standalone_logging is not None
        assert ScriptProgressLogger is not None
        assert detect_standalone_context is not None
    
    def test_common_patterns(self):
        """Test common patterns from QUICKSTART.md lines 1330-1334."""
        # From QUICKSTART.md:
        # Common patterns
        logger1 = setup_script_logging("my_script.py")                    # Script
        logger2 = setup_cli_logging("myapp", verbosity=1)                # CLI
        
        # Custom config example
        custom_config = StormLoggerConfig(log_level=LogLevel.DEBUG)
        logger3 = get_standalone_logger("worker", custom_config)          # Service
        
        progress = ScriptProgressLogger("data_import")                    # Progress
        
        # All patterns should work
        assert logger1 is not None
        assert logger2 is not None
        assert logger3 is not None
        assert progress is not None


class TestStandaloneEnvironmentVariables:
    """Test environment variable handling."""
    
    @patch.dict(os.environ, {'APP_ENV': 'production'})
    def test_app_env_variable(self):
        """Test APP_ENV variable from QUICKSTART.md."""
        # Should respect environment variable
        env = os.getenv("APP_ENV", "development")
        assert env == "production"
    
    @patch.dict(os.environ, {'LOG_LEVEL': 'DEBUG'})
    def test_log_level_variable(self):
        """Test LOG_LEVEL variable from QUICKSTART.md."""
        # Should respect log level override
        level = os.getenv("LOG_LEVEL", "INFO")
        assert level == "DEBUG"


class TestAdvancedFeatures:
    """Test advanced features mentioned in QUICKSTART.md."""
    
    @patch('storm_logger.get_logger')
    def test_business_intelligence_features(self, mock_get_logger):
        """Test business intelligence from QUICKSTART.md lines 1349-1368."""
        mock_logger = Mock()
        mock_get_logger.return_value = mock_logger
        
        # From QUICKSTART.md:
        from storm_logger import get_logger
        logger = get_logger(__name__)
        
        # Track business metrics
        logger.business_metric("users_online", 1500)
        logger.business_metric("revenue", 10000.50, threshold=5000)
        
        # Performance monitoring
        logger.performance_metric("api_response", 0.2, threshold=0.5)
        logger.performance_metric("database_query", 0.05)
        
        # Test results
        logger.test_result("test_login", "passed", 0.1)
        logger.test_result("test_checkout", "failed", 0.8)
        
        # Security events
        logger.security_event("failed_login", "Multiple failed attempts", "warning")
        logger.security_event("suspicious_activity", "Unusual access pattern", "error")
        
        # Verify all calls were made
        assert mock_logger.business_metric.call_count == 2
        assert mock_logger.performance_metric.call_count == 2
        assert mock_logger.test_result.call_count == 2
        assert mock_logger.security_event.call_count == 2
    
    @patch('storm_logger.get_professional_logger')
    def test_professional_logger(self, mock_get_prof_logger):
        """Test professional logger from QUICKSTART.md lines 1371-1380."""
        mock_logger = Mock()
        mock_get_prof_logger.return_value = mock_logger
        
        # From QUICKSTART.md:
        from storm_logger import get_professional_logger
        
        # Enhanced logger with business intelligence
        logger = get_professional_logger(__name__)
        
        logger.info("Operation started")
        logger.business_metric("processing_time", 0.5, "< 1s")
        logger.success("Operation completed successfully")
        
        # Verify calls
        mock_logger.info.assert_called_with("Operation started")
        mock_logger.business_metric.assert_called_with("processing_time", 0.5, "< 1s")
        mock_logger.success.assert_called_with("Operation completed successfully")


# Run specific test categories with pytest markers
pytestmark = [pytest.mark.functional, pytest.mark.standalone]