"""Samsung Health provider — push-based, no OAuth.

Data arrives via the Android companion app POSTing to
POST /api/devices/sync/samsung_health. The companion app reads from
Android Health Connect, which Samsung Health writes to once the user
enables the integration in Samsung Health → Settings → Health Connect.
"""
from bson import ObjectId

from app.models.device_reading import DeviceReading, VALID_METRICS

PROVIDER_NAME = 'samsung_health'
DISPLAY_NAME = 'Samsung Health'

# These match exactly the metrics emitted by android/.../health/HealthReader.kt
SUPPORTED_METRICS = [
    'steps',
    'calories_total',
    'calories_intake',
    'sleep_duration',
    'heart_rate_resting',
    'blood_oxygen',
    'weight',
    'body_fat',
    'basal_metabolic_rate',
    'blood_glucose',
    'blood_pressure_sys',
    'blood_pressure_dia',
]


def normalize_incoming_payload(
    user_id: str, connection_id: str, readings: list[dict]
) -> list[DeviceReading]:
    """Validate and convert readings from the Android companion app."""
    result: list[DeviceReading] = []
    for r in readings:
        metric = r.get('metric', '')
        if metric not in VALID_METRICS:
            continue
        try:
            value = float(r['value'])
        except (KeyError, TypeError, ValueError):
            continue

        result.append(DeviceReading(
            userId=ObjectId(user_id),
            connectionId=ObjectId(connection_id),
            metric=metric,
            date=r.get('date', ''),
            value=value,
            unit=r.get('unit', ''),
            metricType=r.get('metricType', 'daily_summary'),
            subMetrics=r.get('subMetrics') or {},
            quality=r.get('quality', 'good'),
            rawData=r,
        ))
    return result
