import json, subprocess, sys

# Get workouts JSON
result = subprocess.run(["hevy", "workouts", "--limit", "10", "--kg", "--json"], 
                       capture_output=True, text=True, timeout=30)
raw = result.stdout

# Find JSON start
idx = raw.find('[')
if idx < 0:
    idx = raw.find('{')
if idx >= 0:
    data = json.loads(raw[idx:])
else:
    print("NO JSON FOUND:", raw[:200])
    sys.exit(1)

if isinstance(data, list):
    workouts = data
elif isinstance(data, dict) and 'workouts' in data:
    workouts = data['workouts']
else:
    workouts = []

# Find last D2 Upper
for w in workouts:
    title = w.get('title', '')
    if 'D2' in title and 'Upper' in title:
        print(f"ID: {w.get('id')} | {title} | {w.get('start_time')}")
        break
else:
    print("No D2 Upper found")
    # List all titles
    for w in workouts[:8]:
        print(f"  {w.get('id')} | {w.get('title')} | {w.get('start_time')}")
