#!/usr/bin/env python3
"""VitalTrends morning readiness brief.

Reads today's WHOOP recovery from the VitalTrends REST API, falls back to
Oura readiness when no WHOOP row is ready, and prints a three-line brief
(green, yellow or red, with a reason). Optionally posts the brief 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. Use the
                         same timezone as your VitalTrends profile. Defaults to
                         this computer's local timezone.
  SLACK_WEBHOOK_URL      Optional Slack incoming webhook URL. When set, the
                         brief is also posted there (unless --dry-run).
  VITALTRENDS_API_BASE   Optional. Defaults to https://vitaltrends.net/api/v1

Usage:
  python3 morning-brief.py            # print, and post if SLACK_WEBHOOK_URL is set
  python3 morning-brief.py --dry-run  # print only
"""

import argparse
import os
import sys
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"

# WHOOP's own recovery colors: green 67-100, yellow 34-66, red 0-33.
WHOOP_GREEN_MIN = 67
WHOOP_YELLOW_MIN = 34
# Template defaults for Oura readiness. These are not Oura's official bands; change them to suit you.
OURA_GREEN_MIN = 85
OURA_YELLOW_MIN = 70
# Less sleep than this turns a green day yellow.
SHORT_SLEEP_MINUTES = 6 * 60

SUGGESTIONS = {
    "GREEN": "Suggestion: a normal or hard session fits today if you feel good.",
    "YELLOW": "Suggestion: train if you like, but keep the hardest work moderate.",
    "RED": "Suggestion: favor easy movement, recovery and an early night.",
}


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


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


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", "a minute")
        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 format_minutes(minutes):
    if minutes is None:
        return "unknown"
    minutes = int(round(minutes))
    return f"{minutes // 60}h {minutes % 60:02d}m"


def whoop_brief(session, today):
    """Return the brief lines from today's WHOOP row, or None when it is not ready."""
    body = get_json(session, "/whoop/daily", {
        "start": (today - timedelta(days=1)).isoformat(),
        "per_page": 5,
    })
    rows = body.get("data") or []
    # api.md: select the row whose cycle_start_date is today's local date and
    # require both recovery_score and sleep_duration_minutes.
    row = next((r for r in rows
                if r.get("cycle_start_date") == today.isoformat()
                and r.get("recovery_score") is not None
                and r.get("sleep_duration_minutes") is not None), None)
    if row is None:
        return None

    score = float(row["recovery_score"])
    sleep = row.get("sleep_duration_minutes")
    if score >= WHOOP_GREEN_MIN:
        status, reason = "GREEN", f"WHOOP recovery {score:.0f}%"
    elif score >= WHOOP_YELLOW_MIN:
        status, reason = "YELLOW", f"WHOOP recovery {score:.0f}%"
    else:
        status, reason = "RED", f"WHOOP recovery {score:.0f}%"
    if status == "GREEN" and sleep is not None and sleep < SHORT_SLEEP_MINUTES:
        status, reason = "YELLOW", f"WHOOP recovery {score:.0f}% but short sleep"

    details = [f"Sleep {format_minutes(sleep)}"]
    if row.get("sleep_performance_pct") is not None:
        details.append(f"sleep performance {float(row['sleep_performance_pct']):.0f}%")
    if row.get("hrv_rmssd_milli") is not None:
        details.append(f"HRV {float(row['hrv_rmssd_milli']):.0f} ms")
    if row.get("resting_heart_rate") is not None:
        details.append(f"resting HR {row['resting_heart_rate']} bpm")

    return [
        f"Readiness {today.isoformat()}: {status} ({reason})",
        ", ".join(details),
        f"{SUGGESTIONS[status]} Not medical advice.",
    ]


def oura_brief(session, today):
    """Return the brief lines from today's Oura readiness, or None when it is not ready."""
    body = get_json(session, "/oura/daily-readiness", {
        "start": today.isoformat(),
        "end": today.isoformat(),
    })
    rows = body.get("data") or []
    row = next((r for r in rows if r.get("date") == today.isoformat() and r.get("score") is not None), None)
    if row is None:
        return None

    score = int(row["score"])
    if score >= OURA_GREEN_MIN:
        status = "GREEN"
    elif score >= OURA_YELLOW_MIN:
        status = "YELLOW"
    else:
        status = "RED"

    details = []
    if row.get("temperature_deviation") is not None:
        details.append(f"temperature deviation {float(row['temperature_deviation']):+.1f} °C")
    if row.get("contributor_hrv_balance") is not None:
        details.append(f"HRV balance {row['contributor_hrv_balance']}")
    if row.get("contributor_sleep_balance") is not None:
        details.append(f"sleep balance {row['contributor_sleep_balance']}")
    if row.get("contributor_previous_night") is not None:
        details.append(f"previous night {row['contributor_previous_night']}")

    return [
        f"Readiness {today.isoformat()}: {status} (Oura readiness {score})",
        ("Oura contributors: " + ", ".join(details)) if details else "No Oura contributor details yet.",
        f"{SUGGESTIONS[status]} Not medical advice.",
    ]


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 False
    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 False
    if response.status_code >= 400:
        print(f"Slack post failed with HTTP {response.status_code}.", file=sys.stderr)
        return False
    return True


def main():
    parser = argparse.ArgumentParser(description="Print a VitalTrends morning readiness brief.")
    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).")

    today = local_today()
    session = api_session(api_key)

    lines = None
    try:
        lines = whoop_brief(session, today)
        if lines is None:
            lines = oura_brief(session, today)
    except ApiError as exc:
        sys.exit(str(exc))

    if lines is None:
        lines = [
            f"Readiness {today.isoformat()}: NO DATA YET",
            "No WHOOP recovery or Oura readiness for today has synced to VitalTrends.",
            "Try again after your device syncs, or open the VitalTrends dashboard to refresh.",
        ]

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

    webhook = os.environ.get("SLACK_WEBHOOK_URL", "").strip()
    if webhook and not args.dry_run:
        if post_to_slack(webhook, text):
            print("Posted to Slack.", file=sys.stderr)


if __name__ == "__main__":
    main()
