#!/usr/bin/env python3
"""Quiet daily Apple Health Drive sync.
Prints only when new records were imported, so cron can stay silent otherwise.
"""
from __future__ import annotations
import json, subprocess, sys
from pathlib import Path

SCRIPT = Path('/home/agent/.hermes/assets/Gesundheit/scripts/apple_health_drive_sync.py')
cmd = [sys.executable, str(SCRIPT)]
proc = subprocess.run(cmd, text=True, capture_output=True)
if proc.returncode != 0:
    print(proc.stderr or proc.stdout or f"Apple Health sync failed with {proc.returncode}")
    raise SystemExit(proc.returncode)
try:
    data = json.loads(proc.stdout)
    inserted = 0
    for r in data.get('import', {}).get('results', []):
        inserted += int(r.get('inserted') or 0)
    downloaded = data.get('downloaded') or []
    if inserted or downloaded:
        print(f"Apple Health Sync: {inserted} neue Records importiert; {len(downloaded)} Datei(en) heruntergeladen.")
except Exception:
    # If parsing breaks, emit output so it can be diagnosed.
    print(proc.stdout)
