#!/usr/bin/env python3
"""
Claude Code skill for Garmin health data synchronization.

This skill can be invoked in Claude Code to manually trigger health data sync.

Usage in Claude Code:
    User: "sync my health data"
    User: "update garmin data"
"""

import sys
from pathlib import Path

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

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


def main() -> int:
    """Execute health data sync and return results.

    Returns:
        Exit code (0 for success, 1 for failure)
    """
    print("🏥 Garmin Health Data Sync\n")

    try:
        # Initialize sync service
        sync_service = HealthDataSync()

        # Authenticate
        print("🔐 Authenticating with Garmin Connect China...")
        sync_service.authenticate()
        print("✅ Authentication successful\n")

        # Perform incremental sync
        print("🔄 Syncing new health data...\n")
        results = sync_service.sync_incremental()

        # Display results
        print("📊 Sync Results:")
        total_synced = 0
        total_errors = 0

        for metric_type, stats in results.items():
            synced = stats.get("synced", 0)
            errors = stats.get("errors", 0)

            if synced > 0 or errors > 0:
                total_synced += synced
                total_errors += errors

                status_icon = "✓" if errors == 0 else "⚠"
                error_msg = f" ({errors} errors)" if errors > 0 else ""
                print(f"  {status_icon} {metric_type:20} {synced:3} new records{error_msg}")

        if total_synced == 0:
            print("  ℹ️  All data is already up to date!")

        print(f"\n{'✅' if total_errors == 0 else '⚠️ '} Sync complete: {total_synced} records synced")

        return 0 if total_errors == 0 else 1

    except GarminAuthError as e:
        print(f"\n❌ Authentication failed: {e}")
        print("   Please check your Garmin credentials in the .env file.")
        return 1

    except Exception as e:
        print(f"\n❌ Sync failed: {e}")
        import traceback
        traceback.print_exc()
        return 1


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