---
description: Get personalized health advice based on today's data
argument-hint: [diet info] [alcohol] [supplements] [body feelings]
allowed-tools: Bash(./h.sh:*), Bash(python:*), Read
context: fork
model: sonnet
---

# Health Advice Generator

Generate personalized sleep, diet, and exercise recommendations based on:
- Today's health metrics (sleep, HRV, stress, activities)
- User-provided context (diet, alcohol, supplements, body feelings)

## Step 1A: Fetch Today's Health Data

First, get today's health summary:

!`./h.sh show`

## Step 1B: Fetch Long-term Health Trends (Past 2 Years)

Get comprehensive trend analysis to understand baseline patterns:

!`source venv/bin/activate && python3 << 'PYTHON_SCRIPT'
from slack_bot.tools.health_read import HealthReader
from datetime import date, timedelta

# Analyze past 2 years of data
end = date.today()
start = end - timedelta(days=730)

print("🔍 Fetching long-term health trends...\n")

analysis = HealthReader.get_aggregated_analysis(
    start_date=start.isoformat(),
    end_date=end.isoformat(),
    metrics=['rhr', 'hrv', 'sleep', 'stress', 'steps']
)

print(analysis)
PYTHON_SCRIPT
`

## Step 2: Load Manual Logs (if exist)

Check if user has logged manual data today:

!`source venv/bin/activate && python3 << 'PYTHON_SCRIPT'
from datetime import date
from health.services.manual_log_storage import ManualLogStorage

storage = ManualLogStorage()
log = storage.load_log(date.today())

if not (log.diet_entries or log.alcohol_entries or log.supplement_entries or log.feeling_entries or log.fasting_mode):
    print("No manual logs found for today")
else:
    print("=" * 80)
    print(f"📋 Manual Logs for {log.log_date}")
    print("=" * 80)

    if log.fasting_mode:
        print(f"\n🍽️  Fasting Mode: {log.fasting_mode}")

    if log.diet_entries:
        print("\n🍴 Diet entries:")
        for entry in sorted(log.diet_entries, key=lambda x: x.time):
            print(f"  [{entry.time}] {entry.meal_type}: {entry.description}")
            if entry.carbs:
                print(f"    Carbs: {entry.carbs}")

    if log.alcohol_entries:
        print("\n🍷 Alcohol consumption:")
        for entry in sorted(log.alcohol_entries, key=lambda x: x.time):
            print(f"  [{entry.time}] {entry.drink_type}: {entry.amount}")
            print(f"    NAC taken: {'Yes' if entry.nac_taken else 'No'}")

    if log.supplement_entries:
        print("\n💊 Supplements:")
        for entry in sorted(log.supplement_entries, key=lambda x: x.time):
            dosage = f" ({entry.dosage})" if entry.dosage else ""
            print(f"  [{entry.time}] {entry.supplement_name}{dosage}")

    if log.feeling_entries:
        print("\n🩺 Body feelings:")
        for entry in sorted(log.feeling_entries, key=lambda x: x.time):
            severity = f" {entry.severity}/10" if entry.severity else ""
            print(f"  [{entry.time}] {entry.feeling_type}{severity}: {entry.description}")

    print("=" * 80)
PYTHON_SCRIPT
`

## Step 3: Load User Health Profile

Read the user's health profile and protocols:

@health.md

## Step 4: Analyze Additional User Input

User provided additional context (if any): $ARGUMENTS

Combine manual logs with any additional context provided.

## Step 5: Generate Personalized Advice

Based on TODAY'S health data, LONG-TERM TRENDS (from Step 1B), user profile, manual logs, and any additional context, provide:

### 🌙 Sleep Optimization Advice
- Analyze sleep quality (duration, deep/REM ratio, sleep score)
- Consider yesterday's training intensity (from activities)
- Check stress levels and body battery
- Recommend:
  - Optimal bedtime
  - Pre-sleep routine adjustments
  - Magnesium timing (MUST take before bed per protocol)
  - Stretching needs (especially if heavy upper body training)

### 🍽️ Diet & Fasting Decision for Tomorrow
- Review today's fasting mode and effectiveness
- Consider tomorrow's planned activities
- Check if recovery is needed (post heavy lifting?)
- Recommend tomorrow's protocol:
  - PSMF (if recovery needed after heavy lifting or high stress)
  - OMAD (if low stress and no heavy training yesterday)
  - Water Fast (if inflammation detected)
  - Berberine usage rules (NO if alcohol planned, with high-carb meals only)

### 🏃 Exercise Recommendations
- Analyze today's training volume and intensity
- Check HRV status and body battery
- Consider injury protocols:
  - Right foot: Avoid high-impact, prefer elliptical
  - Left foot: Use arch support if hiking
  - Chest tightness: MUST do chest stretches if upper body training
- Recommend:
  - Training type for tomorrow (strength/cardio/rest)
  - Zone 2 cardio duration if applicable (130-140 bpm on elliptical)
  - Anti-glycolytic rule: NO Zone 4 sprints on fasting days
  - Recovery needs (ice foot, stretch chest, etc.)

### ⚠️ Risk Alerts
- Alcohol GABA rebound risk (if alcohol consumed today)
- Chest tightness protocol (door frame stretch, W-raise, resistance band)
- Berberine + alcohol danger (hypoglycemia risk)
- CNS overstimulation affecting sleep (post heavy training)

## Output Format

Present the advice in a clear, actionable format:

```
================================================================================
🤖 Health Advice for [Date]
================================================================================

📊 TODAY'S SUMMARY:
- Sleep: X hrs (Deep: Y, REM: Z, Score: A/100)
- HRV: X ms (Status: BALANCED/UNBALANCED)
- Stress: Avg X/100
- Body Battery: +X/-Y
- Activities: [list with duration and avg HR]
- User Context: [parsed from input]

📈 LONG-TERM TRENDS (2-Year Baseline):
- Resting HR: [yearly trend, recent 30-day status]
- HRV: [yearly trend, recovery status %]
- Sleep Quality: [average duration, deep/REM ratios]
- Stress Levels: [average, high-stress day %]
- Activity: [daily steps average, active day %]

================================================================================
🌙 SLEEP OPTIMIZATION
================================================================================
[Specific advice based on data and protocols]

================================================================================
🍽️ TOMORROW'S DIET STRATEGY
================================================================================
[Fasting decision tree result and supplement timing]

================================================================================
🏃 EXERCISE RECOMMENDATIONS
================================================================================
[Training type, intensity, injury protocols]

================================================================================
⚠️ IMPORTANT ALERTS
================================================================================
[Risk warnings if applicable]

================================================================================
```

## Important Rules

1. **Be specific**: Don't give generic advice. Use the actual numbers from today's data AND compare with long-term baselines.
2. **Context-aware**: If today's metrics deviate from the 2-year trend (e.g., RHR elevated vs baseline), investigate why and adjust advice.
3. **Follow protocols**: Strictly adhere to health.md rules (e.g., no Berberine with alcohol).
4. **Risk-aware**: Prioritize injury prevention and metabolic safety.
5. **Decision tree**: Clearly explain WHY each recommendation is made based on the logic in health.md AND trend data.
6. **Actionable**: Each recommendation should be something the user can immediately act on.

## Example Usage

**With manual logs already recorded:**
```
/health-advice
```

**With additional context:**
```
/health-advice planning to do heavy bench press tomorrow, should I?
```

**If you haven't logged manually yet, you can provide context as arguments:**
```
/health-advice ate PSMF lunch (protein powder + egg), dinner (tuna salad). No alcohol. Took fish oil and B complex. Feeling slight chest tightness.
```

**Note:** It's recommended to use the dedicated logging commands first:
- `/log-diet` for meals
- `/log-alcohol` for drinks
- `/log-supplement` for supplements
- `/log-feeling` for body symptoms

Then run `/health-advice` to get comprehensive analysis.
