from health.analytics.engine import HealthAnalyst
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)

class AnalyticsTool:
    @staticmethod
    def get_health_insights(analysis_type: str, lookback_days: int = 30) -> str:
        """
        Get advanced health insights and correlations.
        
        Args:
            analysis_type: Type of analysis to run. Options:
                - 'recovery_correlations': Impact of Alcohol/Activity on Sleep/RHR.
                - 'fitness_trends': Trends in RHR vs Activity over time.
                - 'lifestyle_impact': Efficacy of Fasting and Supplements.
            lookback_days: Number of days to analyze (default 30, max 365).
        """
        try:
            analyst = HealthAnalyst()
            
            if analysis_type == "recovery_correlations":
                results = analyst.analyze_recovery_correlations(days=lookback_days)
                return f"Recovery Correlations (Last {lookback_days} days):\n{results}"
                
            elif analysis_type == "fitness_trends":
                results = analyst.analyze_fitness_trends(days=lookback_days)
                return f"Fitness Trends (Last {lookback_days} days):\n{results}"
                
            elif analysis_type == "lifestyle_impact":
                results = analyst.analyze_lifestyle_impact(days=lookback_days)
                return f"Lifestyle Impact Analysis (Last {lookback_days} days):\n{results}"
            
            else:
                return f"Unknown analysis type: {analysis_type}. Supported: recovery_correlations, fitness_trends, lifestyle_impact."

        except Exception as e:
            logger.error(f"Error generating insights: {e}")
            return f"Error analyzing data: {str(e)}"

    @staticmethod
    def analyze_driver(driver_metric: str, target_metric: str, method: str = "correlation", lookback_days: int = 30) -> str:
        """
        Analyze specific relationships between two metrics.
        
        Args:
            driver_metric: The cause (e.g., 'alcohol_units', 'steps', 'fasting_mode', 'has_magnesium').
            target_metric: The effect (e.g., 'sleep', 'rhr', 'hrv').
            method: 'correlation' (for continuous values) or 'group_compare' (for yes/no events).
            lookback_days: Days to analyze.
        """
        try:
            analyst = HealthAnalyst()
            
            if method == "correlation":
                # Default to 0 lag for general, but maybe 1 for recovery?
                # Let's default to same-day unless it's known delayed metrics
                lag = 0
                if target_metric in ['sleep', 'rhr', 'hrv'] and driver_metric in ['alcohol_units', 'stress']:
                    lag = 1 # Assumptions for common drivers
                    
                result = analyst.analyze_lagged_correlation(driver_metric, target_metric, lag=lag, days=lookback_days)
                return f"Correlation Analysis ({driver_metric} -> {target_metric}, lag={lag}d):\n{result}"
                
            elif method == "group_compare":
                result = analyst.compare_groups(driver_metric, target_metric, days=lookback_days)
                return f"Group Comparison ({driver_metric} YES vs NO -> {target_metric}):\n{result}"
                
            else:
                return f"Unknown method: {method}"
                
        except Exception as e:
            logger.error(f"Error in analyze_driver: {e}")
            return f"Error: {e}"
