from datetime import date
from health.services.data_sync import HealthDataSync
from health.utils.logging_config import setup_logger
from health.utils.time_utils import get_cst_today

logger = setup_logger(__name__)

class GarminTool:
    @staticmethod
    def sync_garmin(target_date: str = None) -> str:
        """
        Sync health data from Garmin Connect.
        Args:
            target_date: YYYY-MM-DD or None (defaults to today)
        """
        try:
            # 确保使用正确的日期：如果提供了日期参数，检查是否为有效日期，否则使用今天
            if target_date:
                date_obj = date.fromisoformat(target_date)
                today = get_cst_today()
                # 如果模型传递的日期不是今天，默认使用今天的日期
                if date_obj < today:
                    logger.warning(f"Model requested sync for {date_obj}, but defaulting to today ({today})")
                    date_obj = today
            else:
                date_obj = get_cst_today()
            
            logger.info(f"Starting Garmin sync for {date_obj}...")
            sync = HealthDataSync()
            sync.authenticate()
            
            # Sync for the specific single date, force update
            results = sync.sync_all_metrics(date_obj, date_obj, force=True)
            
            summary_parts = []
            for metric, stats in results.items():
                if stats.get("synced", 0) > 0:
                    summary_parts.append(f"{metric}: {stats['synced']} files")
            
            if not summary_parts:
                return f"Sync complete for {date_obj}, but no new data found."
            
            # If we synced successfully, fetch the latest data to return to the user
            from .health_read import HealthReader
            latest_stats = HealthReader.get_daily_detailed_stats(target_date=date_obj.isoformat())
            
            return f"Successfully synced Garmin data for {date_obj}: {', '.join(summary_parts)}.\n\nLatest Stats: {latest_stats}"

        except Exception as e:
            logger.error(f"Garmin sync error: {e}")
            return f"Error syncing Garmin: {str(e)}"
