# Zielesystem: Vereinheitlichte Analyse beider Fachkonzepte

**Datum:** 26. März 2026
**Basis:**
- `.claude/docs/functional/GOALS_VITALS.md` (v9e Spec)
- `.claude/docs/functional/mitai_jinkendo_konzept_diagramme_auswertungen_v2.md`

---

## 1. Wichtige Erkenntnis: BEIDE Konzepte sind komplementär!

### GOALS_VITALS.md definiert:
- **Konkrete Zielwerte** (z.B. "82kg bis 30.06.2026")
- 8 Zieltypen (Gewicht, KF%, VO2Max, etc.)
- Primär-/Nebenziel-Konzept
- Trainingsphasen (automatische Erkennung)
- Aktive Tests (Cooper, Liegestütze, etc.)
- 13 neue KI-Platzhalter

### Konzept v2 definiert:
- **Goal Modes** (strategische Ausrichtung: weight_loss, strength, etc.)
- Score-Gewichtung je Goal Mode
- Chart-Priorisierung je Goal Mode
- Regelbasierte Interpretationen

### Zusammenspiel:
```
Goal MODE (v2)      →  "weight_loss" (strategische Ausrichtung)
  ↓
Primary GOAL (v9e)  →  "82kg bis 30.06.2026" (konkretes Ziel)
Secondary GOAL      →  "16% Körperfett"
  ↓
Training PHASE (v9e) →  "Kaloriendefizit" (automatisch erkannt)
  ↓
Score Weights (v2)  →  body_progress: 0.30, nutrition: 0.25, ...
  ↓
Charts (v2)         →  Zeigen gewichtete Scores + Fortschritt zu Zielen
```

---

## 2. Zwei-Ebenen-Architektur

### Ebene 1: STRATEGIC (Goal Modes aus v2)
**Was:** Grundsätzliche Trainingsausrichtung
**Werte:** weight_loss, strength, endurance, recomposition, health
**Zweck:** Bestimmt Score-Gewichtung und Interpretations-Kontext
**Beispiel:** "Ich will Kraft aufbauen" → mode: strength

### Ebene 2: TACTICAL (Goal Targets aus v9e)
**Was:** Konkrete messbare Ziele
**Werte:** "82kg bis 30.06.2026", "VO2Max 55 ml/kg/min", "50 Liegestütze"
**Zweck:** Fortschritts-Tracking, Prognosen, Motivation
**Beispiel:** "Ich will 82kg wiegen" → target: Gewichtsziel

### Beide zusammen = Vollständiges Zielesystem

---

## 3. Überarbeitetes Datenmodell

### Tabelle: `profiles` (erweitern)
```sql
-- Strategic Goal Mode (aus v2)
ALTER TABLE profiles ADD COLUMN goal_mode VARCHAR(50) DEFAULT 'health';

COMMENT ON COLUMN profiles.goal_mode IS
  'Strategic goal mode: weight_loss, strength, endurance, recomposition, health.
   Determines score weights and interpretation context.';
```

### Tabelle: `goals` (NEU, aus v9e)
```sql
CREATE TABLE goals (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,

  -- Goal Classification
  goal_type VARCHAR(50) NOT NULL,  -- weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
  is_primary BOOLEAN DEFAULT false,
  status VARCHAR(20) DEFAULT 'active',  -- draft, active, reached, abandoned, expired

  -- Target Values
  target_value DECIMAL(10,2),
  current_value DECIMAL(10,2),
  start_value DECIMAL(10,2),
  unit VARCHAR(20),  -- kg, %, ml/kg/min, bpm, mmHg, cm, reps

  -- Timeline
  start_date DATE DEFAULT CURRENT_DATE,
  target_date DATE,
  reached_date DATE,

  -- Metadata
  name VARCHAR(100),  -- z.B. "Sommerfigur 2026"
  description TEXT,

  -- Progress Tracking
  progress_pct DECIMAL(5,2),  -- Auto-calculated: (current - start) / (target - start) * 100

  -- Timestamps
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW(),

  -- Constraints
  CHECK (progress_pct >= 0 AND progress_pct <= 100),
  CHECK (status IN ('draft', 'active', 'reached', 'abandoned', 'expired'))
);

-- Only one primary goal per profile
CREATE UNIQUE INDEX idx_goals_primary ON goals(profile_id, is_primary) WHERE is_primary = true;

-- Index for active goals lookup
CREATE INDEX idx_goals_active ON goals(profile_id, status) WHERE status = 'active';
```

### Tabelle: `training_phases` (NEU, aus v9e)
```sql
CREATE TABLE training_phases (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,

  -- Phase Type
  phase_type VARCHAR(50) NOT NULL,
  -- Werte: calorie_deficit, calorie_maintenance, calorie_surplus,
  --        conditioning, hiit, max_strength, regeneration, competition_prep

  -- Detection
  detected_automatically BOOLEAN DEFAULT false,
  confidence_score DECIMAL(3,2),  -- 0.00-1.00

  -- Status
  status VARCHAR(20) DEFAULT 'suggested',  -- suggested, confirmed, active, ended

  -- Timeline
  start_date DATE,
  end_date DATE,

  -- Metadata
  detection_reason TEXT,  -- Why was this phase detected?
  user_notes TEXT,

  -- Timestamps
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- Only one active phase per profile
CREATE UNIQUE INDEX idx_phases_active ON training_phases(profile_id, status) WHERE status = 'active';
```

### Tabelle: `fitness_tests` (NEU, aus v9e)
```sql
CREATE TABLE fitness_tests (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,

  -- Test Type
  test_type VARCHAR(50) NOT NULL,
  -- Standard: cooper, step_test, pushups, squats, sit_reach, balance, grip_strength
  -- Custom: user_defined

  -- Result
  result_value DECIMAL(10,2) NOT NULL,
  result_unit VARCHAR(20) NOT NULL,  -- meters, bpm, reps, cm, seconds, kg

  -- Test Date
  test_date DATE NOT NULL,

  -- Evaluation
  norm_category VARCHAR(30),  -- very_good, good, average, needs_improvement
  percentile DECIMAL(5,2),  -- Where user ranks vs. norm (0-100)

  -- Trend
  improvement_vs_last DECIMAL(10,2),  -- % change from previous test

  -- Metadata
  notes TEXT,
  conditions TEXT,  -- e.g., "Nach 3h Schlaf, erkältet"

  -- Next Test Recommendation
  recommended_retest_date DATE,

  created_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX idx_fitness_tests_profile_type ON fitness_tests(profile_id, test_type, test_date DESC);
```

---

## 4. Vereinheitlichte API-Struktur

### Goal Modes (Strategic)
```python
# routers/goals.py

@router.get("/modes")
def get_goal_modes():
    """Get all strategic goal modes with score weights."""
    return GOAL_MODES  # From v2 concept

@router.post("/set-mode")
def set_goal_mode(goal_mode: str, session=Depends(require_auth)):
    """Set user's strategic goal mode."""
    # Updates profiles.goal_mode
```

### Goal Targets (Tactical)
```python
@router.get("/targets")
def get_goal_targets(session=Depends(require_auth)):
    """Get all active goal targets."""
    profile_id = session['profile_id']
    # Returns list from goals table
    # Includes: primary + all secondary goals

@router.post("/targets")
def create_goal_target(goal: GoalCreate, session=Depends(require_auth)):
    """Create a new goal target."""
    # Inserts into goals table
    # Auto-calculates progress_pct

@router.get("/targets/{goal_id}")
def get_goal_detail(goal_id: str, session=Depends(require_auth)):
    """Get detailed goal info with history."""
    # Returns goal + progress history + prognosis

@router.put("/targets/{goal_id}/progress")
def update_goal_progress(goal_id: str, session=Depends(require_auth)):
    """Recalculate goal progress."""
    # Auto-called after new measurements
    # Updates current_value, progress_pct

@router.post("/targets/{goal_id}/reach")
def mark_goal_reached(goal_id: str, session=Depends(require_auth)):
    """Mark goal as reached."""
    # Sets status='reached', reached_date=today
```

### Training Phases
```python
@router.get("/phases/current")
def get_current_phase(session=Depends(require_auth)):
    """Get active training phase."""

@router.get("/phases/detect")
def detect_phase(session=Depends(require_auth)):
    """Run phase detection algorithm."""
    # Analyzes last 14 days
    # Returns suggested phase + confidence + reasoning

@router.post("/phases/confirm")
def confirm_phase(phase_id: str, session=Depends(require_auth)):
    """Confirm detected phase."""
    # Sets status='active'
```

### Fitness Tests
```python
@router.get("/tests/types")
def get_test_types():
    """Get all available fitness tests."""

@router.post("/tests/{test_type}/execute")
def record_test_result(
    test_type: str,
    result_value: float,
    result_unit: str,
    session=Depends(require_auth)
):
    """Record a fitness test result."""
    # Inserts into fitness_tests
    # Auto-calculates norm_category, percentile, improvement

@router.get("/tests/due")
def get_due_tests(session=Depends(require_auth)):
    """Get tests that are due for retesting."""
```

---

## 5. Neue KI-Platzhalter (kombiniert aus beiden Konzepten)

### Strategic (aus v2)
```python
{{goal_mode}}                       # "weight_loss"
{{goal_mode_label}}                 # "Gewichtsreduktion"
{{goal_mode_description}}           # "Fettabbau bei Erhalt der Magermasse"
```

### Tactical - Primary Goal (aus v9e)
```python
{{primary_goal_type}}               # "weight"
{{primary_goal_name}}               # "Sommerfigur 2026"
{{primary_goal_target}}             # "82 kg bis 30.06.2026"
{{primary_goal_current}}            # "85.2 kg"
{{primary_goal_start}}              # "86.1 kg"
{{primary_goal_progress_pct}}       # "72%"
{{primary_goal_progress_text}}      # "72% erreicht (4 kg von 5,5 kg)"
{{primary_goal_days_remaining}}     # "45 Tage"
{{primary_goal_prognosis}}          # "Ziel voraussichtlich in 6 Wochen erreicht (3 Wochen früher!)"
{{primary_goal_on_track}}           # "true"
```

### Tactical - Secondary Goals (aus v9e)
```python
{{secondary_goals_count}}           # "2"
{{secondary_goals_list}}            # "16% Körperfett, VO2Max 55 ml/kg/min"
{{secondary_goal_1_type}}           # "body_fat"
{{secondary_goal_1_progress}}       # "45%"
```

### Training Phase (aus v9e)
```python
{{current_phase}}                   # "calorie_deficit"
{{current_phase_label}}             # "Kaloriendefizit"
{{phase_since}}                     # "seit 14 Tagen"
{{phase_confidence}}                # "0.92"
{{phase_recommendation}}            # "Krafttraining erhalten, Cardio moderat, Proteinzufuhr 2g/kg"
{{phase_detected_automatically}}    # "true"
```

### Fitness Tests (aus v9e)
```python
{{test_last_cooper}}                # "2.800m (VO2Max ~52) vor 3 Wochen"
{{test_last_cooper_date}}           # "2026-03-05"
{{test_last_cooper_result}}         # "2800"
{{test_last_cooper_vo2max}}         # "52.3"
{{test_last_cooper_category}}       # "good"
{{test_due_list}}                   # "Sit & Reach (seit 5 Wochen), Liegestütze (seit 4 Wochen)"
{{test_next_recommended}}           # "Cooper-Test (in 2 Wochen fällig)"
{{fitness_score_overall}}           # "72/100"
{{fitness_score_endurance}}         # "good"
{{fitness_score_strength}}          # "average"
{{fitness_score_flexibility}}       # "needs_improvement"
```

### GESAMT: 35+ neue Platzhalter aus v9e
Plus die 84 aus v2 = **120+ neue Platzhalter total**

---

## 6. Überarbeitete Implementierungs-Roadmap

### Phase 0a: Minimal Goal System (3-4h) ⭐ **JETZT**

**Strategic Layer:**
- DB: `goal_mode` in profiles
- Backend: GOAL_MODES aus v2
- API: GET/SET goal mode
- UI: Goal Mode Selector (5 Modi)

**Tactical Layer:**
- DB: `goals` table
- API: CRUD für goal targets
- UI: Goal Management Page (minimal)
  - Liste aktiver Ziele
  - Fortschrittsbalken
  - "+ Neues Ziel" Button

**Aufwand:** 3-4h (erweitert wegen Tactical Layer)

---

### Phase 0b: Goal-Aware Placeholders (16-20h)

**Strategic Placeholders:**
```python
{{goal_mode}}                       # Aus profiles.goal_mode
{{goal_mode_label}}                 # Aus GOAL_MODES mapping
```

**Tactical Placeholders:**
```python
{{primary_goal_type}}               # Aus goals WHERE is_primary=true
{{primary_goal_target}}
{{primary_goal_progress_pct}}
{{primary_goal_prognosis}}          # Berechnet aus Trend
```

**Score Calculations (goal-aware):**
```python
def get_body_progress_score(profile_id: str) -> str:
    profile = get_profile_data(profile_id)
    goal_mode = profile.get('goal_mode', 'health')

    # Get weights from v2 concept
    weights = GOAL_MODES[goal_mode]['score_weights']

    # Calculate sub-scores
    fm_score = calculate_fm_progress(profile_id)
    lbm_score = calculate_lbm_progress(profile_id)

    # Weight according to goal mode
    if goal_mode == 'weight_loss':
        total = 0.50 * fm_score + 0.30 * weight_score + 0.20 * lbm_score
    elif goal_mode == 'strength':
        total = 0.60 * lbm_score + 0.30 * fm_score + 0.10 * weight_score
    # ...

    return f"{int(total)}/100"
```

---

### Phase 0c: Training Phases (4-6h) **PARALLEL**

**DB:**
- `training_phases` table

**Detection Algorithm:**
```python
def detect_current_phase(profile_id: str) -> dict:
    """Detects training phase from last 14 days of data."""

    # Analyze data
    kcal_balance = get_kcal_balance_14d(profile_id)
    training_dist = get_training_distribution_14d(profile_id)
    weight_trend = get_weight_trend_14d(profile_id)
    hrv_avg = get_hrv_avg_14d(profile_id)
    volume_change = get_volume_change_14d(profile_id)

    # Phase Detection Rules
    if kcal_balance < -300 and weight_trend < 0:
        return {
            'phase': 'calorie_deficit',
            'confidence': 0.85,
            'reason': f'Avg kcal balance {kcal_balance}/day, weight -0.5kg/week'
        }

    if training_dist['endurance'] > 60 and vo2max_trend > 0:
        return {
            'phase': 'conditioning',
            'confidence': 0.78,
            'reason': f'{training_dist["endurance"]}% cardio, VO2max improving'
        }

    if volume_change < -40 and hrv_avg < hrv_baseline * 0.85:
        return {
            'phase': 'regeneration',
            'confidence': 0.92,
            'reason': f'Volume -40%, HRV below baseline, recovery needed'
        }

    # Default
    return {
        'phase': 'maintenance',
        'confidence': 0.50,
        'reason': 'No clear pattern detected'
    }
```

**API:**
- GET /phases/current
- GET /phases/detect
- POST /phases/confirm

**UI:**
- Dashboard Badge: "📊 Phase: Kaloriendefizit"
- Phase Detection Banner: "Wir haben erkannt: Kaloriendefizit-Phase. Stimmt das?"

---

### Phase 0d: Fitness Tests (4-6h) **SPÄTER**

**DB:**
- `fitness_tests` table

**Test Definitions:**
```python
FITNESS_TESTS = {
    'cooper': {
        'name': 'Cooper-Test',
        'description': '12 Minuten laufen, maximale Distanz',
        'unit': 'meters',
        'interval_weeks': 6,
        'norm_tables': {  # Simplified
            'male_30-39': {'very_good': 2800, 'good': 2500, 'average': 2200},
            'female_30-39': {'very_good': 2500, 'good': 2200, 'average': 1900}
        },
        'calculate_vo2max': lambda distance: (distance - 504.9) / 44.73
    },
    'pushups': {
        'name': 'Liegestütze-Test',
        'description': 'Maximale Anzahl ohne Pause',
        'unit': 'reps',
        'interval_weeks': 4,
        'norm_tables': { ... }
    },
    # ... weitere Tests
}
```

**UI:**
- Tests Page mit Testliste
- Test Execution Flow (Anleitung → Eingabe → Auswertung)
- Test History mit Trend-Chart

---

## 7. Priorisierte Reihenfolge

### SOFORT (3-4h)
**Phase 0a:** Minimal Goal System (Strategic + Tactical)
- Basis für alles andere
- User kann Ziele setzen
- Score-Berechnungen können goal_mode nutzen

### DIESE WOCHE (16-20h)
**Phase 0b:** Goal-Aware Placeholders
- 84 Platzhalter aus v2
- 35+ Platzhalter aus v9e
- **TOTAL: 120+ Platzhalter**

### PARALLEL (4-6h)
**Phase 0c:** Training Phases
- Automatische Erkennung
- Phase-aware Recommendations

### SPÄTER (4-6h)
**Phase 0d:** Fitness Tests
- Enhancement, nicht kritisch für Charts

---

## 8. Kritische Erkenntnisse

### 1. GOALS_VITALS.md ist detaillierter
- Konkrete Implementierungs-Specs
- DB-Schema-Vorschläge
- 13 definierte KI-Platzhalter
- **ABER:** Fehlt Score-Gewichtung (das hat v2)

### 2. Konzept v2 ist strategischer
- Goal Modes mit Score-Gewichtung
- Chart-Interpretationen
- Regelbasierte Logik
- **ABER:** Fehlt konkrete Ziel-Tracking (das hat v9e)

### 3. Beide zusammen = Vollständig
- v2 (Goal Modes) + v9e (Goal Targets) = Komplettes Zielesystem
- v2 (Scores) + v9e (Tests) = Vollständiges Assessment
- v2 (Charts) + v9e (Phases) = Kontext-aware Visualisierung

### 4. Meine ursprüngliche Analyse war incomplete
- Ich hatte nur v2 betrachtet
- v9e fügt kritische Details hinzu
- **Neue Gesamt-Schätzung:** 120+ Platzhalter (statt 84)

---

## 9. Aktualisierte Empfehlung

**JA zu Phase 0a (Minimal Goal System), ABER erweitert:**

### Was Phase 0a umfassen muss (3-4h):

1. **Strategic Layer (aus v2):**
   - goal_mode in profiles
   - GOAL_MODES Definition
   - GET/SET endpoints

2. **Tactical Layer (aus v9e):**
   - goals Tabelle
   - CRUD für Ziele
   - Fortschritts-Berechnung

3. **UI:**
   - Goal Mode Selector (Settings)
   - Goal Management Page (Basic)
   - Dashboard Goal Widget

### Was kann warten:
- Training Phases → Phase 0c (parallel)
- Fitness Tests → Phase 0d (später)
- Vollständige Test-Integration → v9f

---

## 10. Nächste Schritte

**JETZT:**
1. Phase 0a implementieren (3-4h)
   - Strategic + Tactical Goal System
2. Dann Phase 0b (Goal-Aware Placeholders, 16-20h)
3. Parallel Phase 0c (Training Phases, 4-6h)

**Soll ich mit Phase 0a (erweitert) starten?**
- Beide Goal-Konzepte integriert
- Ready für 120+ Platzhalter
- Basis für intelligentes Coach-System

**Commit:** ae93b9d (muss aktualisiert werden)
**Neue Analyse:** GOALS_SYSTEM_UNIFIED_ANALYSIS.md
