#!/usr/bin/env python3
"""
DEPRECATED — Weight data now comes exclusively from Health Connect.

Health Connect syncs daily via health_sync.py (launchd, 9 AM).
Your Nexus Pro scale → Health Connect app → Google Drive zip → health_sync.py → dashboard.

If you need to manually trigger a weight sync:
  python3 ~/clawd/health_sync.py

This file is kept as a fallback only. If used, it tags the entry
as 'manual' so it's clear it didn't come from the normal pipeline.
"""

import sys
import json
from pathlib import Path
from datetime import date, datetime

DASHBOARD = Path(__file__).resolve().parent / "dashboard-data.json"
BASELINE = 245.0
GOAL = 220.0

def main():
    if len(sys.argv) < 2:
        print("⚠️  Weight data now comes from Health Connect automatically.")
        print("   To manually trigger a sync: python3 ~/clawd/health_sync.py")
        print()
        print("   To force a manual override (not recommended):")
        print("   python3 log_weight.py <weight> [body_fat%] [muscle_mass]")
        sys.exit(0)

    new_weight = float(sys.argv[1])
    body_fat = float(sys.argv[2]) if len(sys.argv) > 2 else None
    muscle_mass = float(sys.argv[3]) if len(sys.argv) > 3 else None

    data = json.loads(DASHBOARD.read_text())
    w = data.get("weight", {})

    old_weight = w.get("current", new_weight)
    delta = round(new_weight - old_weight, 1)

    series = w.get("series30d", [])
    series.append(new_weight)
    if len(series) > 30:
        series = series[-30:]

    last_7 = series[-7:] if len(series) >= 7 else series
    avg7d = round(sum(last_7) / len(last_7), 1)

    if len(series) >= 7:
        weekly_pace = round((new_weight - series[-7]), 1)
    else:
        weekly_pace = w.get("weeklyPace", -1.5)

    lost_so_far = round(BASELINE - new_weight, 1)
    remaining = new_weight - GOAL
    eta_weeks = round(remaining / abs(weekly_pace)) if weekly_pace < 0 and remaining > 0 else 0

    today = date.today()

    w.update({
        "current": new_weight,
        "avg7d": avg7d,
        "goal": GOAL,
        "baseline": BASELINE,
        "baselineDate": "February 1st",
        "deltaVsLast": delta,
        "pace": weekly_pace,
        "paceUnit": "lb/wk",
        "etaWeeks": eta_weeks,
        "lastWeighIn": today.isoformat(),
        "series30d": series,
        "lostSoFar": lost_so_far,
        "weeklyPace": abs(weekly_pace),
        "projectedWeeks": float(eta_weeks),
        "date": today.isoformat(),
        "synced_at": datetime.now().isoformat(),
        "source": "manual override",
    })

    if body_fat is not None:
        w["bodyFat"] = body_fat
    if muscle_mass is not None:
        w["muscleMass"] = muscle_mass

    data["weight"] = w
    data["date"] = today.isoformat()
    DASHBOARD.write_text(json.dumps(data, indent=2))

    arrow = "↓" if delta <= 0 else "↑"
    print(f"⚠️  MANUAL OVERRIDE: {new_weight} lbs ({arrow}{abs(delta)} from last)")
    print(f"   7-day avg: {avg7d} | Lost so far: {lost_so_far} lbs")
    print(f"   Next Health Connect sync will overwrite this.")


if __name__ == "__main__":
    main()
