#!/usr/bin/env python3
"""iHealth Evening Sync - Update Kitzu profile with latest weight/BP data."""

import json
import os
from datetime import datetime, timezone, timedelta

# Paths
PROFILE_PATH = "/Users/bsyrros/clawd/kitzu/data/unified/profile.json"
WEIGHT_RAW_PATH = "/Users/bsyrros/clawd/kitzu/data/ihealth/weight_raw.json"
BP_RAW_PATH = "/Users/bsyrros/clawd/kitzu/data/ihealth/bp_raw.json"

# The weight data fetched from iHealth API
WEIGHT_API_RESPONSE = {
  "CurrentRecordCount": 13,
  "WeightDataList": [
    {"BMI": 30.93, "BoneValue": 10.36, "DataID": "b1da3cc56eb96663971b4fbe9a4fa297", "DataSource": "FromDevice", "FatValue": 28.9, "MDate": 1774682665, "MuscaleValue": 156.31, "VFR": 13, "WaterValue": 52, "WeightValue": 234.44, "measurement_time": "2026-03-28 07:24:25"},
    {"BMI": 31.10, "BoneValue": 10.14, "DataID": "172c64c604a5764a666eae614bf78de5", "DataSource": "FromDevice", "FatValue": 29.0, "MDate": 1774768143, "MuscaleValue": 157.19, "VFR": 13, "WaterValue": 52, "WeightValue": 235.76, "measurement_time": "2026-03-29 07:09:03"},
    {"BMI": 31.23, "BoneValue": -1, "DataID": "0d7c3e5625d681444f204f483c2acb2a", "DataSource": "FromDevice", "FatValue": -1, "MDate": 1774781930, "MuscaleValue": -1, "VFR": 0, "WaterValue": -1, "WeightValue": 236.69, "measurement_time": "2026-03-29 10:58:50"},
    {"BMI": 30.86, "BoneValue": 10.14, "DataID": "27e06fcb3fcee121f7fe07623a5853a7", "DataSource": "FromDevice", "FatValue": 28.6, "MDate": 1774789051, "MuscaleValue": 156.97, "VFR": 13, "WaterValue": 52.3, "WeightValue": 233.93, "measurement_time": "2026-03-29 12:57:31"},
    {"BMI": 30.90, "BoneValue": 10.36, "DataID": "9aaf9180db983edc43e84a6a6874daf4", "DataSource": "FromDevice", "FatValue": 28.7, "MDate": 1774854415, "MuscaleValue": 156.53, "VFR": 13, "WaterValue": 52.1, "WeightValue": 234.22, "measurement_time": "2026-03-30 07:06:55"},
    {"BMI": 30.81, "BoneValue": 10.36, "DataID": "7470871416480a6add2ea0fddc8e72fb", "DataSource": "FromDevice", "FatValue": 28.6, "MDate": 1774879308, "MuscaleValue": 156.31, "VFR": 13, "WaterValue": 52.2, "WeightValue": 233.49, "measurement_time": "2026-03-30 14:01:48"},
    {"BMI": 31.03, "BoneValue": 10.36, "DataID": "dfcc6fcc66c765115ecd6e1df2a65dc5", "DataSource": "FromDevice", "FatValue": 28.8, "MDate": 1774942478, "MuscaleValue": 157.19, "VFR": 13, "WaterValue": 52.1, "WeightValue": 235.23, "measurement_time": "2026-03-31 07:34:38"},
    {"BMI": 30.86, "BoneValue": 10.14, "DataID": "0fa8334ad0f48a217ce6b23838be9683", "DataSource": "FromDevice", "FatValue": 28.1, "MDate": 1774968069, "MuscaleValue": 158.07, "VFR": 13, "WaterValue": 52.7, "WeightValue": 233.89, "measurement_time": "2026-03-31 14:41:09"},
    {"BMI": 30.87, "BoneValue": 10.36, "DataID": "99d5d26425209a487afd91995802c910", "DataSource": "FromDevice", "FatValue": 28.0, "MDate": 1775002026, "MuscaleValue": 158.29, "VFR": 13, "WaterValue": 52.8, "WeightValue": 234.02, "measurement_time": "2026-04-01 00:07:06"},
    {"BMI": 30.70, "BoneValue": 10.36, "DataID": "10682ae6a629217d9fdf63ddf22c9c78", "DataSource": "FromDevice", "FatValue": 27.9, "MDate": 1775028492, "MuscaleValue": 157.63, "VFR": 13, "WaterValue": 52.9, "WeightValue": 232.70, "measurement_time": "2026-04-01 07:28:12"},
    {"BMI": 30.56, "BoneValue": 10.14, "DataID": "c87ac004d58798caae9ace6e94b7814e", "DataSource": "FromDevice", "FatValue": 27.8, "MDate": 1775070628, "MuscaleValue": 157.19, "VFR": 13, "WaterValue": 52.9, "WeightValue": 231.60, "measurement_time": "2026-04-01 19:10:28"},
    {"BMI": 30.81, "BoneValue": 10.14, "DataID": "8aef6efaf04f57e7241337f23387261e", "DataSource": "FromDevice", "FatValue": 28.3, "MDate": 1775113647, "MuscaleValue": 157.19, "VFR": 13, "WaterValue": 52.5, "WeightValue": 233.49, "measurement_time": "2026-04-02 07:07:27"},
    {"BMI": 30.87, "BoneValue": 10.36, "DataID": "f4ccc5c958303181204bf58600d6fc67", "DataSource": "FromDevice", "FatValue": 28.4, "MDate": 1775200551, "MuscaleValue": 157.19, "VFR": 13, "WaterValue": 52.4, "WeightValue": 233.98, "measurement_time": "2026-04-03 07:15:51"}
  ]
}

BP_API_RESPONSE = {"BPDataList": [], "CurrentRecordCount": 0}


def load_json(path, default=None):
    try:
        with open(path, 'r') as f:
            content = f.read().strip()
            if not content:
                return default if default is not None else {}
            return json.loads(content)
    except (FileNotFoundError, json.JSONDecodeError):
        return default if default is not None else {}


def save_json(path, data):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'w') as f:
        json.dump(data, f, indent=2)


def get_date_from_measurement(mt):
    return mt.split(' ')[0]


def main():
    weight_list = WEIGHT_API_RESPONSE.get("WeightDataList", [])
    bp_list = BP_API_RESPONSE.get("BPDataList", [])

    # --- Load existing raw data ---
    existing_weight_raw = load_json(WEIGHT_RAW_PATH, default=[])
    existing_bp_raw = load_json(BP_RAW_PATH, default=[])

    existing_weight_ids = {r.get("DataID") for r in existing_weight_raw if isinstance(r, dict)}
    new_weight_records = [r for r in weight_list if r["DataID"] not in existing_weight_ids]
    merged_weight_raw = existing_weight_raw + new_weight_records

    existing_bp_ids = {r.get("DataID") for r in existing_bp_raw if isinstance(r, dict)}
    new_bp_records = [r for r in bp_list if r.get("DataID") not in existing_bp_ids]
    merged_bp_raw = existing_bp_raw + new_bp_records

    save_json(WEIGHT_RAW_PATH, merged_weight_raw)
    save_json(BP_RAW_PATH, merged_bp_raw)

    # --- Update Kitzu profile ---
    profile = load_json(PROFILE_PATH, default={})
    if "vitals" not in profile:
        profile["vitals"] = {}
    vitals = profile["vitals"]

    sorted_weights = sorted(weight_list, key=lambda x: x["MDate"])
    latest = sorted_weights[-1]

    vitals["weight"] = {
        "value_lbs": round(latest["WeightValue"], 1),
        "bmi": round(latest["BMI"], 1),
        "date": latest["measurement_time"],
        "source": "iHealth Nexus Pro"
    }

    valid_comp = [w for w in sorted_weights if w.get("FatValue", -1) > 0]
    if valid_comp:
        lc = valid_comp[-1]
        vitals["body_composition"] = {
            "body_fat_pct": round(lc["FatValue"], 1),
            "muscle_mass_lbs": round(lc["MuscaleValue"], 1),
            "bone_mass_lbs": round(lc["BoneValue"], 1) if lc.get("BoneValue", -1) > 0 else None,
            "water_pct": round(lc["WaterValue"], 1) if lc.get("WaterValue", -1) > 0 else None,
            "visceral_fat_rating": lc.get("VFR", None),
            "date": lc["measurement_time"],
            "source": "iHealth Nexus Pro"
        }

    if "weight_history" not in vitals:
        vitals["weight_history"] = []
    existing_dates = {e.get("date") for e in vitals["weight_history"]}
    for w in sorted_weights:
        mt = w["measurement_time"]
        if mt not in existing_dates:
            vitals["weight_history"].append({
                "date": mt,
                "value_lbs": round(w["WeightValue"], 1),
                "bmi": round(w["BMI"], 1),
                "body_fat_pct": round(w["FatValue"], 1) if w.get("FatValue", -1) > 0 else None,
                "source": "iHealth Nexus Pro"
            })
            existing_dates.add(mt)
    vitals["weight_history"] = sorted(vitals["weight_history"], key=lambda x: x["date"])

    # 7-day trend from morning weigh-ins
    morning_weights = {}
    for w in sorted_weights:
        date = get_date_from_measurement(w["measurement_time"])
        time_str = w["measurement_time"].split(' ')[1]
        hour = int(time_str.split(':')[0])
        if hour < 12:
            if date not in morning_weights or w["MDate"] < morning_weights[date]["MDate"]:
                morning_weights[date] = w

    if len(morning_weights) >= 2:
        sorted_days = sorted(morning_weights.keys())
        first_val = morning_weights[sorted_days[0]]["WeightValue"]
        last_val = morning_weights[sorted_days[-1]]["WeightValue"]
        vitals["weight_trend_7d"] = {
            "start_date": sorted_days[0],
            "end_date": sorted_days[-1],
            "start_lbs": round(first_val, 1),
            "end_lbs": round(last_val, 1),
            "change_lbs": round(last_val - first_val, 1),
            "direction": "down" if last_val < first_val else "up" if last_val > first_val else "flat"
        }

    vitals["last_sync"] = datetime.now(timezone.utc).isoformat()
    if "blood_pressure" not in vitals:
        vitals["blood_pressure"] = None
    if "bp_history" not in vitals:
        vitals["bp_history"] = []

    save_json(PROFILE_PATH, profile)

    # --- Summary ---
    print("=" * 50)
    print("iHealth Evening Sync Summary")
    print("=" * 50)
    print(f"New weight records added to raw: {len(new_weight_records)}")
    print(f"New BP records added to raw: {len(new_bp_records)}")
    print(f"Total weight records in raw file: {len(merged_weight_raw)}")
    print(f"Total weight history entries in profile: {len(vitals['weight_history'])}")
    print()
    print(f"Latest weight: {round(latest['WeightValue'], 1)} lbs ({latest['measurement_time']})")
    print(f"Latest BMI: {round(latest['BMI'], 1)}")
    if valid_comp:
        lc = valid_comp[-1]
        print(f"Latest body fat: {round(lc['FatValue'], 1)}%")
        print(f"Latest muscle mass: {round(lc['MuscaleValue'], 1)} lbs")
        print(f"Latest water %: {round(lc['WaterValue'], 1)}%")
        print(f"Visceral fat rating: {lc.get('VFR')}")
    print()
    if "weight_trend_7d" in vitals:
        t = vitals["weight_trend_7d"]
        print(f"7-day weight trend: {t['start_lbs']} -> {t['end_lbs']} lbs ({t['change_lbs']:+.1f} lbs, {t['direction']})")
        print(f"  Period: {t['start_date']} to {t['end_date']}")
    print()
    print("Latest BP: No new BP readings in the last 7 days")
    print(f"Sync timestamp: {vitals['last_sync']}")
    print("=" * 50)


if __name__ == "__main__":
    main()
