#!/usr/bin/env python3
import os
import sys
import subprocess
from pathlib import Path
from datetime import datetime

BASE = Path('/root/.openclaw/workspace/skills/Openclaw-With-Apple/scripts')
LOCAL_HEALTH_DIR = Path('/root/.openclaw/workspace/skills/Openclaw-With-Apple/data/health')
LOG_DIR = Path('/root/.openclaw/workspace/skills/Openclaw-With-Apple/logs')
ICLOUD_TOOL = BASE / 'icloud_tool.py'
HEALTH_TOOL = BASE / 'health_tool.py'

LOCAL_HEALTH_DIR.mkdir(parents=True, exist_ok=True)
LOG_DIR.mkdir(parents=True, exist_ok=True)

def run(cmd, env=None):
    return subprocess.run(cmd, text=True, capture_output=True, env=env)

def main():
    ts = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC')
    env = os.environ.copy()
    env.setdefault('ICLOUD_USERNAME', 'netlee1010@gmail.com')
    env['ICLOUD_CHINA'] = '0'
    env.pop('icloud_china', None)

    print(f'=== health_sync_and_analyze @ {ts} ===')

    # 1) 探测目录
    probe = run(['python3', str(ICLOUD_TOOL), 'drive', 'list', 'Shortcuts/Health'], env=env)
    print(probe.stdout)
    if probe.returncode != 0:
        print(probe.stderr)
        print('Health 目录暂不存在或尚未生成文件，任务结束。')
        return 0

    # 2) 直接拉取目录索引（借助 drive list 输出文件名），逐个下载 health_* 文件
    lines = [l.strip() for l in probe.stdout.splitlines()]
    names = []
    for line in lines:
        if line.startswith('📄 '):
            name = line[2:].strip()
            if name.startswith('health_'):
                name = name.split('  (')[0].strip()
                names.append(name)

    if not names:
        print('Health 目录已存在，但还没有 health_* 文件。')
        return 0

    for name in names:
        target = LOCAL_HEALTH_DIR / name
        dl = run(['python3', str(ICLOUD_TOOL), 'drive', 'download', f'Shortcuts/Health/{name}', str(target)], env=env)
        print(dl.stdout)
        if dl.returncode != 0:
            print(dl.stderr)

    # 3) 分析今天；如果今天没有，就分析目录最近数据
    today = run(['python3', str(HEALTH_TOOL), 'today', str(LOCAL_HEALTH_DIR)], env=env)
    if today.stdout:
        print(today.stdout)
    if today.stderr:
        print(today.stderr)

    if today.returncode != 0:
        report = run(['python3', str(HEALTH_TOOL), 'report', str(LOCAL_HEALTH_DIR), '--days', '7'], env=env)
        if report.stdout:
            print(report.stdout)
        if report.stderr:
            print(report.stderr)
        return report.returncode

    return 0

if __name__ == '__main__':
    sys.exit(main())
