import json

with open('/tmp/w6_d1_routine.json') as f:
    full = json.load(f)

# Build safe update body: only top-level routine fields + per-exercise clean sets
exercises_out = []
for ex in full['exercises']:
    new_ex = {
        "exercise_template_id": ex['exercise_template_id'],
        "notes": ex.get('notes', ''),
        "rest_seconds": ex.get('rest_seconds', 0),
    }
    new_sets = []
    for s in ex['sets']:
        ns = {"type": s['type']}
        if s.get('weight_kg') is not None:
            ns['weight_kg'] = s['weight_kg']
        if s.get('reps') is not None:
            ns['reps'] = s['reps']
        if s.get('rep_range') is not None:
            ns['rep_range'] = s['rep_range']
        if s.get('distance_meters') is not None:
            ns['distance_meters'] = s['distance_meters']
        if s.get('duration_seconds') is not None:
            ns['duration_seconds'] = s['duration_seconds']
        if s.get('custom_metric') is not None:
            ns['custom_metric'] = s['custom_metric']
        new_sets.append(ns)
    new_ex['sets'] = new_sets
    exercises_out.append(new_ex)

payload = {
    "routine": {
        "title": full['title'],
        "notes": full.get('notes') or "Min-Max 4x Full Body (W6). Programar cargas W6.",
        "exercises": exercises_out,
    }
}

with open('/tmp/routine_update.json', 'w') as f:
    json.dump(payload, f, indent=2)
print("OK", len(exercises_out), "exercises")
