#!/usr/bin/env python3
"""VitalTrends Withings weight trend.

Reads the last five weeks of Withings weight readings from the VitalTrends REST
API, averages each day's readings, and prints a 7-day moving average with the
change over the last week. When the trend reverses direction (for example from
losing to gaining), it adds a short nudge and can post it to a Slack incoming
webhook.

Read-only: this script only sends GET requests to VitalTrends. It never prints
or logs your API key. Not medical advice.

Requirements: Python 3.9+ and the `requests` package (pip install requests).

Environment variables:
  VITALTRENDS_API_KEY    Required. Your key from https://vitaltrends.net/developer
  VITALTRENDS_TIMEZONE   Optional IANA timezone, e.g. Europe/Lisbon. Defaults to
                         this computer's local timezone.
  SLACK_WEBHOOK_URL      Optional. When set, the summary is posted there only
                         when the trend reverses (unless --dry-run).
  VITALTRENDS_API_BASE   Optional. Defaults to https://vitaltrends.net/api/v1

Usage:
  python3 withings-weight-trend.py
  python3 withings-weight-trend.py --unit lb --threshold 0.3
  python3 withings-weight-trend.py --dry-run
"""

import argparse
import os
import sys
from collections import defaultdict
from datetime import datetime, timedelta
from urllib.parse import urlsplit

try:
    from zoneinfo import ZoneInfo
except ImportError:  # pragma: no cover
    sys.exit("Python 3.9 or newer is required.")

try:
    import requests
except ImportError:
    sys.exit("This script needs the requests package: pip install requests")

API_BASE = os.environ.get("VITALTRENDS_API_BASE", "https://vitaltrends.net/api/v1").rstrip("/")
USER_AGENT = "vitaltrends-automation-template/1.0"
LOOKBACK_DAYS = 34          # enough for three 7-day windows plus gaps
MIN_DAYS_IN_WINDOW = 3      # a 7-day average needs at least this many weigh-in days
KG_PER_LB = 0.45359237


class ApiError(Exception):
    """A VitalTrends API error that should stop the script."""


def local_timezone():
    tz_name = os.environ.get("VITALTRENDS_TIMEZONE", "").strip()
    if tz_name:
        return ZoneInfo(tz_name)
    return datetime.now().astimezone().tzinfo


def api_session(api_key):
    session = requests.Session()
    session.headers.update({
        "Authorization": f"Bearer {api_key}",
        "Accept": "application/json",
        "User-Agent": USER_AGENT,
    })
    return session


def get_json(session, path, params=None):
    url = path if path.startswith("https://") else f"{API_BASE}{path}"
    # Only ever send the API key to the VitalTrends API host.
    if urlsplit(url).netloc != urlsplit(API_BASE).netloc:
        raise ApiError("Refusing to follow a link outside the VitalTrends API.")
    try:
        response = session.get(url, params=params, timeout=30)
    except requests.RequestException as exc:
        raise ApiError(f"Could not reach VitalTrends: {exc.__class__.__name__}") from None
    if response.status_code == 401:
        raise ApiError("VitalTrends rejected the API key (401). Check VITALTRENDS_API_KEY.")
    if response.status_code == 403:
        raise ApiError("VitalTrends refused the request (403). API access needs an active subscription.")
    if response.status_code == 429:
        retry = response.headers.get("Retry-After", "60")
        raise ApiError(f"Rate limit reached (429). Try again in {retry} seconds.")
    if response.status_code >= 400:
        raise ApiError(f"VitalTrends returned HTTP {response.status_code} for {urlsplit(url).path}.")
    return response.json()


def get_all(session, path, params, max_pages=10):
    """Follow links.next on paginated list endpoints."""
    rows, url, query = [], path, dict(params)
    for _ in range(max_pages):
        body = get_json(session, url, query)
        rows.extend(body.get("data") or [])
        next_url = (body.get("links") or {}).get("next")
        if not next_url:
            break
        url, query = next_url, None
    return rows


def daily_weights(rows, tz):
    """Average all weight readings per local calendar day."""
    by_day = defaultdict(list)
    for row in rows:
        weight = row.get("weight_kg")
        measured = row.get("measured_at")
        if weight is None or not measured:
            continue
        try:
            measured_at = datetime.fromisoformat(str(measured).replace("Z", "+00:00"))
        except ValueError:
            continue
        by_day[measured_at.astimezone(tz).date()].append(float(weight))
    return {day: sum(values) / len(values) for day, values in by_day.items()}


def moving_average(daily, end_day):
    """Mean of daily weights in the 7 days ending on end_day, or None when too sparse."""
    values = [daily[end_day - timedelta(days=offset)]
              for offset in range(7)
              if (end_day - timedelta(days=offset)) in daily]
    if len(values) < MIN_DAYS_IN_WINDOW:
        return None
    return sum(values) / len(values)


def direction(change, threshold):
    if change is None:
        return None
    if change >= threshold:
        return "up"
    if change <= -threshold:
        return "down"
    return "flat"


def post_to_slack(webhook_url, text):
    if not webhook_url.startswith("https://"):
        print("SLACK_WEBHOOK_URL must start with https://. Not posting.", file=sys.stderr)
        return
    try:
        response = requests.post(webhook_url, json={"text": text}, timeout=15)
    except requests.RequestException as exc:
        print(f"Slack post failed: {exc.__class__.__name__}", file=sys.stderr)
        return
    if response.status_code >= 400:
        print(f"Slack post failed with HTTP {response.status_code}.", file=sys.stderr)


def main():
    parser = argparse.ArgumentParser(description="Print a Withings 7-day moving average weight trend.")
    parser.add_argument("--unit", choices=["kg", "lb"], default="kg", help="display unit (default kg)")
    parser.add_argument("--threshold", type=float, default=0.2,
                        help="weekly change in kg that counts as a trend (default 0.2)")
    parser.add_argument("--dry-run", action="store_true", help="print only, never post to Slack")
    args = parser.parse_args()

    api_key = os.environ.get("VITALTRENDS_API_KEY", "").strip()
    if not api_key:
        sys.exit("Set VITALTRENDS_API_KEY to your VitalTrends API key (Settings -> Developer).")

    tz = local_timezone()
    today = datetime.now(tz).date()
    try:
        rows = get_all(api_session(api_key), "/withings/measurements", {
            "start": (today - timedelta(days=LOOKBACK_DAYS)).isoformat(),
            "end": today.isoformat(),
            "per_page": 200,
        })
    except ApiError as exc:
        sys.exit(str(exc))

    daily = daily_weights(rows, tz)
    if not daily:
        print("No Withings weight readings in the last five weeks. Check that Withings is connected and synced.")
        return

    latest_day = max(daily)
    ma_now = moving_average(daily, latest_day)
    ma_week_ago = moving_average(daily, latest_day - timedelta(days=7))
    ma_two_weeks_ago = moving_average(daily, latest_day - timedelta(days=14))

    def show(value_kg):
        if value_kg is None:
            return "n/a"
        if args.unit == "lb":
            return f"{value_kg / KG_PER_LB:.1f} lb"
        return f"{value_kg:.1f} kg"

    def show_change(change_kg):
        if change_kg is None:
            return "n/a"
        value = change_kg / KG_PER_LB if args.unit == "lb" else change_kg
        return f"{value:+.1f} {args.unit}"

    if ma_now is None:
        print(f"Latest weigh-in {latest_day.isoformat()}: {show(daily[latest_day])}. "
              f"Not enough weigh-ins in the last 7 days for a moving average (need {MIN_DAYS_IN_WINDOW}).")
        return

    recent_change = ma_now - ma_week_ago if ma_week_ago is not None else None
    prior_change = ma_week_ago - ma_two_weeks_ago if (ma_week_ago is not None and ma_two_weeks_ago is not None) else None
    recent_dir = direction(recent_change, args.threshold)
    prior_dir = direction(prior_change, args.threshold)

    lines = [
        f"Weight trend to {latest_day.isoformat()}: 7-day average {show(ma_now)} "
        f"(latest weigh-in {show(daily[latest_day])})",
        f"Change vs last week: {show_change(recent_change)}; week before: {show_change(prior_change)}",
    ]

    reversed_trend = recent_dir in ("up", "down") and prior_dir in ("up", "down") and recent_dir != prior_dir
    if reversed_trend:
        lines.append(f"Nudge: your 7-day average has turned {recent_dir} after trending {prior_dir}. "
                     "Worth a look at the last week's routine. Not medical advice.")
    else:
        lines.append("No trend reversal this week. Not medical advice.")

    text = "\n".join(lines)
    print(text)

    webhook = os.environ.get("SLACK_WEBHOOK_URL", "").strip()
    if webhook and reversed_trend and not args.dry_run:
        post_to_slack(webhook, text)


if __name__ == "__main__":
    main()
