"""
Configuration management for Garmin Health Sync system.

Loads environment variables and defines data type configurations.
"""

import os
from pathlib import Path
from typing import Dict, Any
from dotenv import load_dotenv
from health.utils.env_loader import load_env_with_extras

# Load environment variables
load_env_with_extras()

# Project paths
PROJECT_ROOT = Path(__file__).parent.parent

# Support environment override for testing
_data_dir_env = os.getenv("DATA_DIR")
if _data_dir_env:
    DATA_DIR = Path(_data_dir_env)
else:
    DATA_DIR = PROJECT_ROOT / "data" / "health"

DB_PATH = DATA_DIR / "health.db"
LOGS_DIR = PROJECT_ROOT / "logs"
TOKEN_STORE = Path.home() / ".garmin" / "tokens"

# Ensure directories exist
DATA_DIR.mkdir(parents=True, exist_ok=True)
LOGS_DIR.mkdir(parents=True, exist_ok=True)
TOKEN_STORE.mkdir(parents=True, exist_ok=True)

# Garmin credentials (optional during setup, required for actual sync)
GARMIN_EMAIL = os.getenv("GARMIN_EMAIL")
GARMIN_PASSWORD = os.getenv("GARMIN_PASSWORD")


def validate_credentials() -> None:
    """Validate that Garmin credentials are set.

    Raises:
        ValueError: If credentials are missing
    """
    if not GARMIN_EMAIL or not GARMIN_PASSWORD:
        raise ValueError(
            "Missing Garmin credentials. Please set GARMIN_EMAIL and GARMIN_PASSWORD "
            "in your .env file. See .env.example for reference."
        )

# Data type configurations
# Maps each data type to its API method, model, and storage path
DATA_TYPE_CONFIG: Dict[str, Dict[str, Any]] = {
    "steps": {
        "api_method": "get_steps_data",
        "storage_path": "daily_metrics/steps",
        "description": "Daily step count, distance, and calories",
    },
    "heart_rate": {
        "api_method": "get_heart_rates",
        "storage_path": "daily_metrics/heart_rate",
        "description": "Heart rate data including min, max, resting",
    },
    "sleep": {
        "api_method": "get_sleep_data",
        "storage_path": "daily_metrics/sleep",
        "description": "Sleep stages, duration, and quality scores",
    },
    "stress": {
        "api_method": "get_stress_data",
        "storage_path": "daily_metrics/stress",
        "description": "Stress levels throughout the day",
    },
    "body_battery": {
        "api_method": "get_body_battery",
        "storage_path": "daily_metrics/body_battery",
        "description": "Body Battery charge and drain",
    },
    "spo2": {
        "api_method": "get_spo2_data",
        "storage_path": "daily_metrics/spo2",
        "description": "Blood oxygen saturation levels",
    },
    "respiration": {
        "api_method": "get_respiration_data",
        "storage_path": "daily_metrics/respiration",
        "description": "Breathing rate data",
    },
    "hydration": {
        "api_method": "get_hydration_data",
        "storage_path": "daily_metrics/hydration",
        "description": "Daily water intake tracking",
    },
    "floors": {
        "api_method": "get_floors",
        "storage_path": "daily_metrics/floors",
        "description": "Floors climbed per day",
    },
    "intensity_minutes": {
        "api_method": "get_intensity_minutes",
        "storage_path": "daily_metrics/intensity_minutes",
        "description": "Active intensity minutes (moderate and vigorous)",
    },
    "hrv": {
        "api_method": "get_hrv_data",
        "storage_path": "daily_metrics/hrv",
        "description": "Heart rate variability",
    },
    "rhr": {
        "api_method": "get_rhr_day",
        "storage_path": "daily_metrics/rhr",
        "description": "Resting heart rate",
    },
    "activities": {
        "api_method": "get_activities_by_date",
        "storage_path": "activities",
        "description": "Exercise activities and workouts",
        "batch_by_date_range": True,
    },
    "weight": {
        "api_method": "get_weigh_ins",
        "storage_path": "body_metrics/weight",
        "description": "Body weight measurements",
    },
    "lifestyle_logging": {
        "api_method": "get_lifestyle_logging_data",
        "storage_path": "daily_metrics/lifestyle_logging",
        "description": "Lifestyle behaviors: alcohol, caffeine, meals, fasting, light exercise",
    },
}

# Sync settings
DEFAULT_BATCH_SIZE_DAYS = 30  # Process 30 days at a time for batch operations
MAX_RETRIES = 3  # Maximum retry attempts for API calls
RETRY_DELAY_SECONDS = 2  # Initial delay before retrying (exponential backoff)

# Historical data start date (user configurable)
HISTORICAL_START_DATE = "2024-01-01"  # Default, can be overridden via CLI
