#!/usr/bin/env python3
"""
Resync steps data with correct API.

This script re-syncs steps data using the correct daily summary API
instead of the 15-minute interval data.
"""

import sys
from pathlib import Path
from datetime import date, timedelta

sys.path.insert(0, str(Path(__file__).parent.parent))

from health.services.data_sync import HealthDataSync
from health.utils.date_utils import date_range


def resync_steps(start_date: date, end_date: date) -> None:
    """Resync steps data for a date range.

    Args:
        start_date: Start date
        end_date: End date
    """
    print(f"\n🔄 Re-syncing steps data from {start_date} to {end_date}")
    print("=" * 60)

    sync = HealthDataSync()

    # Authenticate
    print("\n🔐 Authenticating...")
    sync.authenticate()

    # Sync each day with force=True to overwrite existing data
    success_count = 0
    error_count = 0

    for target_date in date_range(start_date, end_date):
        try:
            print(f"\n📅 {target_date.isoformat()}: ", end="")
            result = sync.sync_daily_metric("steps", target_date, force=True)

            if result:
                print("✅ Synced")
                success_count += 1
            else:
                print("⏭️  No data available")
        except Exception as e:
            print(f"❌ Error: {e}")
            error_count += 1

    # Summary
    print("\n" + "=" * 60)
    print(f"✅ Successfully synced: {success_count}")
    print(f"❌ Errors: {error_count}")
    print(f"📊 Total processed: {success_count + error_count}")
    print("=" * 60 + "\n")


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description="Re-sync steps data with correct API"
    )
    parser.add_argument(
        "--start",
        type=str,
        default="2026-01-01",
        help="Start date (YYYY-MM-DD)",
    )
    parser.add_argument(
        "--end",
        type=str,
        default=None,
        help="End date (YYYY-MM-DD), default is yesterday",
    )

    args = parser.parse_args()

    start = date.fromisoformat(args.start)
    end = date.fromisoformat(args.end) if args.end else date.today() - timedelta(days=1)

    try:
        resync_steps(start, end)
    except KeyboardInterrupt:
        print("\n\n⚠️  Sync interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n❌ Fatal error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
