#!/usr/bin/env python3
"""
Daily sync script for Garmin health data.

Performs incremental sync to fetch new data since last sync.
Suitable for running as a cron job.

Usage:
    python scripts/daily_sync.py

Cron example (daily at 8:00 AM):
    0 8 * * * cd /path/to/project && /path/to/venv/bin/python scripts/daily_sync.py
"""

import sys
from pathlib import Path
from datetime import datetime

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

from health.services.data_sync import HealthDataSync
from health.utils.logging_config import setup_logger
from health.utils.exceptions import GarminAuthError

logger = setup_logger(__name__, log_file="daily_sync.log")


def main() -> int:
    """Run daily incremental sync.

    Returns:
        Exit code (0 for success, 1 for failure)
    """
    start_time = datetime.now()
    logger.info("=" * 60)
    logger.info(f"Daily Sync Started: {start_time.isoformat()}")
    logger.info("=" * 60)

    try:
        # Initialize sync service
        sync_service = HealthDataSync()

        # Authenticate
        logger.info("Authenticating with Garmin Connect China...")
        sync_service.authenticate()
        logger.info("Authentication successful")

        # Perform incremental sync (including today)
        logger.info("Starting incremental sync...")
        from datetime import date
        results = sync_service.sync_incremental(until_date=date.today())

        # Log results
        total_synced = sum(s.get("synced", 0) for s in results.values())
        total_errors = sum(s.get("errors", 0) for s in results.values())

        logger.info("\nSync Results:")
        for metric_type, stats in results.items():
            synced = stats.get("synced", 0)
            errors = stats.get("errors", 0)

            if synced > 0 or errors > 0:
                logger.info(
                    f"  {metric_type}: {synced} synced, {errors} errors"
                )

        # Final status
        end_time = datetime.now()
        duration = (end_time - start_time).total_seconds()

        logger.info(f"\nDaily Sync Complete!")
        logger.info(f"Total records synced: {total_synced}")
        logger.info(f"Total errors: {total_errors}")
        logger.info(f"Duration: {duration:.2f} seconds")
        logger.info("=" * 60)

        return 0 if total_errors == 0 else 1

    except GarminAuthError as e:
        logger.error(f"Authentication failed: {e}")
        logger.error("Please check Garmin credentials in .env file")
        return 1

    except Exception as e:
        logger.exception(f"Daily sync failed: {e}")
        return 1


if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)
