import subprocess, json

# Re-read the routine to verify it's current and correctly set for W4
result = subprocess.run(
    ["hevy", "routine", "2164feea-1b5f-4822-adb5-aec6e58cdf88", "--json"],
    capture_output=True, text=True, timeout=30
)
raw = result.stdout
idx = raw.find('{')
data = json.loads(raw[idx:])
routine = data if 'routine' not in data else data['routine']

# Build update payload: only safe fields
exercises_out = []
for ex in routine.get('exercises', []):
    sets_out = []
    for s in ex.get('sets', []):
        set_entry = {"type": s.get("type", "normal")}
        if s.get("weight_kg") is not None:
            set_entry["weight_kg"] = s["weight_kg"]
        if s.get("reps") is not None:
            set_entry["reps"] = s["reps"]
        if s.get("rep_range"):
            set_entry["rep_range"] = s["rep_range"]
        if s.get("duration_seconds") is not None:
            set_entry["duration_seconds"] = s["duration_seconds"]
        sets_out.append(set_entry)
    
    ex_out = {
        "exercise_template_id": ex["exercise_template_id"],
        "sets": sets_out,
    }
    if ex.get("notes"):
        ex_out["notes"] = ex["notes"]
    if ex.get("rest_seconds") is not None:
        ex_out["rest_seconds"] = ex["rest_seconds"]
    
    exercises_out.append(ex_out)

update_payload = {
    "routine": {
        "title": routine.get("title", "Min-Max 4x D2 — Upper (W4)"),
        "exercises": exercises_out
    }
}

with open("/tmp/routine_update.json", "w") as f:
    json.dump(update_payload, f, indent=2)

print("Routine payload written. Key weights:")
for ex in exercises_out:
    eid = ex["exercise_template_id"]
    normal_sets = [s for s in ex["sets"] if s["type"] == "normal"]
    weights = [f"{s.get('weight_kg', 'BW')}kg" for s in normal_sets if s.get('weight_kg')]
    if weights:
        print(f"  {eid}: {', '.join(weights)}")
