import functools
import threading
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def monitor(reference_data_path: str, dotenv_path: str = None, wait_for_completion: bool = True):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                result = func(*args, **kwargs)
            except Exception as e:
                logger.error(f"Error in monitored function '{func.__name__}': {e}")
                raise e

            try:
                from .local_runner import run_local_analysis
                
                # Load environment variables if dotenv_path is provided
                if dotenv_path:
                    from dotenv import load_dotenv
                    from pathlib import Path
                    env_path = Path(dotenv_path)
                    if env_path.exists():
                        load_dotenv(env_path)
                    else:
                        logger.warning(f"Dotenv file not found at: {dotenv_path}")
                
                # Create thread - daemon only if not waiting for completion
                analysis_thread = threading.Thread(
                    target=run_local_analysis,
                    args=(func, reference_data_path),
                    daemon=not wait_for_completion
                )
                analysis_thread.start()
                
                # Wait for thread to complete if requested
                if wait_for_completion:
                    logger.info("Waiting for Cortif analysis to complete...")
                    analysis_thread.join()
                    logger.info("Cortif analysis complete!")
                    
            except Exception as e:
                logger.error(f"Failed to start Cortif analysis thread: {e}")
            return result
        return wrapper
    return decorator
