#!/usr/bin/env python3
"""Download Apple Health Auto Export files from Google Drive and import them.

Folder: Gesundheitsdaten Inbox / Apple Health Auto Export
Requires gog CLI credentials for friday.uplink@gmail.com.
"""
from __future__ import annotations
import json, os, subprocess, sys
from pathlib import Path

ACCOUNT = "friday.uplink@gmail.com"
# Actual automation folder created by Health Auto Export. The app created a
# nested "Health Auto Export" folder and placed JSON files there.
DRIVE_FOLDER_ID = "1BPtqp9h72eh5GQZRSszIn-pYKX6AGUaT"
BASE = Path.home() / ".hermes" / "assets" / "Gesundheit"
INBOX = BASE / "inbox" / "apple_health_exports"
IMPORTER = BASE / "scripts" / "apple_health_import.py"
GOG_SECRET_ENV = Path.home() / ".hermes" / "secrets" / "gog_keyring.env"


def load_gog_keyring_password() -> str:
    value = os.environ.get("GOG_KEYRING_PASSWORD", "").strip()
    if value:
        return value
    if not GOG_SECRET_ENV.is_file():
        raise RuntimeError(f"Missing gog keyring secret environment file: {GOG_SECRET_ENV}")
    if GOG_SECRET_ENV.stat().st_mode & 0o077:
        raise RuntimeError(f"Unsafe permissions on gog keyring secret file: {GOG_SECRET_ENV}")
    for raw_line in GOG_SECRET_ENV.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        if line.startswith("export "):
            line = line[7:].strip()
        key, sep, raw_value = line.partition("=")
        if sep and key.strip() == "GOG_KEYRING_PASSWORD":
            secret = raw_value.strip().strip('"').strip("'")
            if secret:
                return secret
    raise RuntimeError(f"GOG_KEYRING_PASSWORD missing in {GOG_SECRET_ENV}")


def run(cmd: list[str], **kwargs):
    env = os.environ.copy()
    env["GOG_KEYRING_PASSWORD"] = load_gog_keyring_password()
    return subprocess.run(cmd, text=True, capture_output=True, env=env, **kwargs)


def main() -> None:
    INBOX.mkdir(parents=True, exist_ok=True)
    ls = run(["gog", "-a", ACCOUNT, "drive", "ls", "--parent", DRIVE_FOLDER_ID, "--json"], check=True)
    data = json.loads(ls.stdout or "{}")
    files = data.get("files", []) if isinstance(data, dict) else data
    wanted = [f for f in files if str(f.get("name", "")).lower().endswith((".json", ".csv"))]
    downloaded = []
    for f in wanted:
        name = f.get("name") or f.get("id")
        fid = f.get("id")
        if not fid:
            continue
        target = INBOX / name
        if target.exists() and target.stat().st_size > 0:
            continue
        dl = run(["gog", "-a", ACCOUNT, "drive", "download", fid, "--output", str(target), "--json"])
        if dl.returncode == 0 and target.exists():
            downloaded.append(str(target))
        else:
            print(f"Download failed for {name}: {dl.stderr or dl.stdout}", file=sys.stderr)
    imp = run([sys.executable, str(IMPORTER), str(INBOX), "--move"], check=True)
    print(json.dumps({"drive_folder_id": DRIVE_FOLDER_ID, "drive_files_seen": len(wanted), "downloaded": downloaded, "import": json.loads(imp.stdout)}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
