#!/usr/bin/env python3
"""
Setup script for Garmin Health Data Sync system.

Initializes database, creates directory structure, and validates configuration.
"""

import sys
from pathlib import Path

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

from health import config
from health.db.schema import init_database
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)


def main() -> None:
    """Initialize health data sync system."""
    print("🏥 Garmin Health Data Sync - Setup\n")

    # Check for .env file
    env_file = config.PROJECT_ROOT / ".env"
    if not env_file.exists():
        print("⚠️  No .env file found!")
        print(f"   Creating from .env.example...\n")

        example_file = config.PROJECT_ROOT / ".env.example"
        if example_file.exists():
            import shutil
            shutil.copy(example_file, env_file)
            print(f"✅ Created .env file at {env_file}")
            print("   ⚠️  IMPORTANT: Edit .env and add your Garmin credentials!\n")
        else:
            print(f"❌ .env.example not found. Please create .env manually.")
            sys.exit(1)

    # Check credentials
    try:
        config.validate_credentials()
        print(f"✅ Garmin credentials configured")
        print(f"   Email: {config.GARMIN_EMAIL}\n")
    except ValueError:
        print("⚠️  Garmin credentials not set in .env file")
        print("   Please edit .env and add GARMIN_EMAIL and GARMIN_PASSWORD\n")

    # Initialize database
    print("🗄️  Initializing database...")
    try:
        init_database()
        print(f"✅ Database initialized at {config.DB_PATH}\n")
    except Exception as e:
        print(f"❌ Database initialization failed: {e}")
        sys.exit(1)

    # Verify data directories
    print("📁 Data directories:")
    print(f"   Data: {config.DATA_DIR}")
    print(f"   Logs: {config.LOGS_DIR}")
    print(f"   Token store: {config.TOKEN_STORE}\n")

    # Summary
    print("✅ Setup complete!\n")
    print("Next steps:")
    print("  1. Ensure your .env file has valid Garmin credentials")
    print("  2. Run 'python -m health.cli.sync status' to check status")
    print("  3. Run 'python -m health.cli.sync sync-incremental' for initial sync")
    print(f"  4. Or run 'python -m health.cli.sync backfill --start-date {config.HISTORICAL_START_DATE}' for historical data")
    print("\n📚 For help, run: python -m health.cli.sync --help")


if __name__ == "__main__":
    main()
