#!/usr/bin/env python3
"""
System verification script for Garmin Health Sync.

Checks that all components are properly installed and configured.
"""

import sys
from pathlib import Path

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


def check_dependencies() -> bool:
    """Check that all required Python packages are installed."""
    print("📦 Checking dependencies...")

    required_packages = [
        ("pydantic", "Pydantic"),
        ("click", "Click"),
        ("garminconnect", "Garmin Connect"),
        ("garth", "Garth"),
        ("dotenv", "python-dotenv"),
    ]

    all_ok = True
    for module_name, display_name in required_packages:
        try:
            __import__(module_name)
            print(f"  ✅ {display_name}")
        except ImportError:
            print(f"  ❌ {display_name} not installed")
            all_ok = False

    return all_ok


def check_modules() -> bool:
    """Check that all health modules can be imported."""
    print("\n🔧 Checking health modules...")

    modules = [
        ("health.config", "Configuration"),
        ("health.db.schema", "Database schema"),
        ("health.db.repository", "Repository"),
        ("health.models.daily_metrics", "Daily metrics models"),
        ("health.models.activity", "Activity models"),
        ("health.models.body_metrics", "Body metrics models"),
        ("health.services.storage", "Storage service"),
        ("health.utils.date_utils", "Date utilities"),
        ("health.utils.logging_config", "Logging config"),
        ("health.utils.exceptions", "Exceptions"),
    ]

    all_ok = True
    for module_name, display_name in modules:
        try:
            __import__(module_name)
            print(f"  ✅ {display_name}")
        except Exception as e:
            print(f"  ❌ {display_name}: {e}")
            all_ok = False

    return all_ok


def check_config() -> bool:
    """Check configuration and credentials."""
    print("\n⚙️  Checking configuration...")

    try:
        from health import config

        print(f"  ✅ Data directory: {config.DATA_DIR}")
        print(f"  ✅ Database path: {config.DB_PATH}")
        print(f"  ✅ Logs directory: {config.LOGS_DIR}")

        # Check if .env exists
        env_file = config.PROJECT_ROOT / ".env"
        if not env_file.exists():
            print(f"\n  ⚠️  .env file not found at {env_file}")
            print(f"     Run 'python scripts/setup_health.py' to create it")
            return False

        # Check credentials
        try:
            config.validate_credentials()
            print(f"  ✅ Garmin credentials configured ({config.GARMIN_EMAIL})")
            return True
        except ValueError:
            print(f"  ⚠️  Garmin credentials not set in .env")
            print(f"     Edit {env_file} and add your credentials")
            return False

    except Exception as e:
        print(f"  ❌ Configuration error: {e}")
        return False


def check_database() -> bool:
    """Check database connectivity."""
    print("\n🗄️  Checking database...")

    try:
        from health.db.repository import HealthRepository

        repo = HealthRepository()
        states = repo.get_all_last_sync_states()
        print(f"  ✅ Database connected ({len(states)} sync states)")
        return True

    except Exception as e:
        print(f"  ❌ Database error: {e}")
        return False


def check_cli() -> bool:
    """Check CLI tools."""
    print("\n⌨️  Checking CLI tools...")

    cli_files = [
        ("health/cli/sync.py", "Sync CLI"),
        ("scripts/setup_health.py", "Setup script"),
        ("scripts/daily_sync.py", "Daily sync script"),
        ("skills/health_sync.py", "Health sync skill"),
    ]

    all_ok = True
    for file_path, display_name in cli_files:
        path = Path(file_path)
        if path.exists():
            print(f"  ✅ {display_name}: {file_path}")
        else:
            print(f"  ❌ {display_name} not found: {file_path}")
            all_ok = False

    return all_ok


def main() -> int:
    """Run all verification checks.

    Returns:
        Exit code (0 if all checks pass, 1 if any fail)
    """
    print("🏥 Garmin Health Data Sync - System Verification\n")
    print("=" * 60)

    checks = [
        ("Dependencies", check_dependencies),
        ("Modules", check_modules),
        ("Configuration", check_config),
        ("Database", check_database),
        ("CLI Tools", check_cli),
    ]

    results = {}
    for name, check_func in checks:
        try:
            results[name] = check_func()
        except Exception as e:
            print(f"\n❌ {name} check failed with exception: {e}")
            results[name] = False

    # Summary
    print("\n" + "=" * 60)
    print("📊 Verification Summary:\n")

    all_passed = True
    for name, passed in results.items():
        status = "✅ PASS" if passed else "❌ FAIL"
        print(f"  {status}: {name}")
        if not passed:
            all_passed = False

    print("\n" + "=" * 60)

    if all_passed:
        print("🎉 All checks passed! System ready to use.\n")
        print("Next steps:")
        print("  1. Run: python scripts/setup_health.py")
        print("  2. Test sync: python -m health.cli.sync sync --days 3")
        print("  3. Check status: python -m health.cli.sync status")
        return 0
    else:
        print("⚠️  Some checks failed. Please fix the issues above.\n")
        return 1


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