"""Device dashboard summary helpers.

Samsung Health is push-only — the Android companion app handles all
data ingestion via /api/devices/sync/samsung_health. There's no
backend-initiated sync to orchestrate, so this module just builds the
dashboard summary the frontend needs.
"""
from app.models.device_reading import VALID_METRICS
from app.repositories import device_repository


def get_dashboard_summary(user_id: str) -> dict:
    """Build a summary dict optimized for the frontend dashboard."""
    all_metrics = list(VALID_METRICS)
    data = device_repository.get_metrics_range(user_id, all_metrics, days=7)

    summary: dict = {}
    for metric, readings in data.items():
        if not readings:
            continue
        latest = readings[-1]
        summary[metric] = {
            "value": latest.value,
            "unit": latest.unit,
            "date": latest.date,
            "provider": latest.provider,
            "subMetrics": latest.subMetrics,
        }

    connections = device_repository.find_connections_by_user(user_id)
    connected = [c.provider for c in connections if c.status == 'active']
    last_sync = None
    for c in connections:
        if c.lastSyncAt and (not last_sync or c.lastSyncAt > last_sync):
            last_sync = c.lastSyncAt

    return {
        "summary": summary,
        "connectedProviders": connected,
        "lastSync": last_sync.isoformat() if last_sync else None,
    }
