#!/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

BASE = Path('/home/agent/.hermes/assets/Gesundheit')
SCRIPT = BASE / 'scripts' / 'apple_health_drive_sync.py'
PIPELINE = BASE / 'scripts' / 'health_pipeline.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:
        dash = subprocess.run([sys.executable, str(PIPELINE), 'dashboard'], text=True, capture_output=True, timeout=180)
        if dash.returncode != 0:
            print(dash.stderr or dash.stdout or f"Dashboard refresh failed with {dash.returncode}")
            raise SystemExit(dash.returncode)
    if inserted or downloaded:
        refreshed = '; Dashboard aktualisiert' if inserted else ''
        print(f"Apple Health Sync: {inserted} neue Records importiert; {len(downloaded)} Datei(en) heruntergeladen{refreshed}.")
except Exception:
    # If parsing breaks, emit output so it can be diagnosed.
    print(proc.stdout)
    raise
