# Training Type Profiles – Umfassendes Trainingsmanagement-System

**Issue:** #15 (erweitert)
**Status:** Phase 1 KOMPLETT ✅ (Foundation + Auto-Evaluation) | Phase 2 ausstehend (Admin-UI)
**Erstellt:** 2026-03-23
**Implementiert:** Phase 1 - 2026-03-23

---

## Vision

Jeder Trainingstyp erhält ein **umfassendes Profil** mit Parametern, die:
1. **Mindestanforderungen** definieren (wann ist es "echtes" Training?)
2. **Intensitätsbereiche** beschreiben (Zonen: regenerativ, moderat, intensiv)
3. **Trainingswirkung** charakterisieren (welche Fähigkeiten werden trainiert?)
4. **Periodisierung** unterstützen (optimale Frequenz, Erholungsbedarf)
5. **Dynamische Bewertung** ermöglichen (ist diese konkrete Aktivität gut/schlecht?)

---

## Trainingstyp-Profil: Vollständige Parameter-Definition

### Struktur (JSONB in training_types.profile)

```json
{
  "version": "1.0",
  "created_at": "2026-03-23",

  // ━━━ 1. MINDESTANFORDERUNGEN (Quality Gates) ━━━
  "minimum_requirements": {
    "enabled": true,
    "rules": {
      "duration_min": {
        "value": 15,
        "weight": 5,
        "reason": "Unter 15min keine signifikante Trainingswirkung"
      },
      "avg_hr_min": {
        "value": 100,
        "weight": 3,
        "reason": "Puls muss für Ausdauerreiz erhöht sein"
      },
      "max_hr_min": {
        "value": 120,
        "weight": 1,
        "reason": "Maximalpuls zeigt echte Belastungsspitze"
      },
      "distance_km": {
        "value": 1.0,
        "weight": 2,
        "reason": "Mindestdistanz für Lauftraining"
      },
      "kcal_active": {
        "value": 100,
        "weight": 1,
        "reason": "Mindest-Energieverbrauch"
      }
    },
    "pass_threshold": 0.6,
    "fail_action": "mark_low_quality"
  },

  // ━━━ 2. INTENSITÄTSBEREICHE (HF-Zonen) ━━━
  "intensity_zones": {
    "method": "percentage_max_hr",  // oder "percentage_reserve_hr"
    "zones": [
      {
        "name": "regenerativ",
        "min_percent": 50,
        "max_percent": 60,
        "color": "#4CAF50",
        "effect": "Erholung, Grundlagenausdauer 1",
        "target_duration_min": 30
      },
      {
        "name": "grundlagenausdauer",
        "min_percent": 60,
        "max_percent": 70,
        "color": "#2196F3",
        "effect": "Aerobe Kapazität, Fettstoffwechsel",
        "target_duration_min": 45
      },
      {
        "name": "entwicklungsbereich",
        "min_percent": 70,
        "max_percent": 80,
        "color": "#FF9800",
        "effect": "VO2max-Training, Laktattoleranz",
        "target_duration_min": 20
      },
      {
        "name": "schwellentraining",
        "min_percent": 80,
        "max_percent": 90,
        "color": "#F44336",
        "effect": "Anaerobe Schwelle, Wettkampftempo",
        "target_duration_min": 10
      },
      {
        "name": "maximale_intensität",
        "min_percent": 90,
        "max_percent": 100,
        "color": "#9C27B0",
        "effect": "Maximalkraft, Sprint, HIIT",
        "target_duration_min": 5
      }
    ],
    "evaluation_rules": {
      "time_in_zone_required": true,
      "min_time_in_target_zone_percent": 70
    }
  },

  // ━━━ 3. TRAININGSWIRKUNG (Abilities Mapping) ━━━
  "training_effects": {
    "primary_abilities": [
      {
        "category": "konditionell",
        "ability": "ausdauer",
        "intensity": 5,
        "description": "Hauptfokus: Aerobe Ausdauer"
      },
      {
        "category": "konditionell",
        "ability": "schnelligkeit",
        "intensity": 2,
        "description": "Nebenfokus: Lauftempo"
      }
    ],
    "secondary_abilities": [
      {
        "category": "koordinativ",
        "ability": "rhythmus",
        "intensity": 3,
        "description": "Laufrhythmus, Schrittfrequenz"
      },
      {
        "category": "psychisch",
        "ability": "willenskraft",
        "intensity": 4,
        "description": "Durchhaltevermögen bei langen Läufen"
      }
    ],
    "metabolic_focus": ["aerobic", "fat_oxidation"],
    "muscle_groups": ["legs_posterior", "legs_anterior", "core"],
    "energy_systems": ["aerobic_oxidative", "anaerobic_lactic"]
  },

  // ━━━ 4. PERIODISIERUNG & FREQUENZ ━━━
  "periodization": {
    "recommended_frequency": {
      "per_week_min": 2,
      "per_week_max": 5,
      "per_week_optimal": 3,
      "consecutive_days_max": 2
    },
    "recovery_requirement": {
      "hours_before_same_type": 48,
      "hours_before_high_intensity": 24,
      "rpe_threshold_for_extra_rest": 8
    },
    "progression": {
      "beginner_duration_min": 20,
      "intermediate_duration_min": 30,
      "advanced_duration_min": 45,
      "volume_increase_percent_per_week": 10
    },
    "deload_recommendation": {
      "every_n_weeks": 4,
      "volume_reduction_percent": 40
    }
  },

  // ━━━ 5. LEISTUNGSINDIKATOREN (KPIs) ━━━
  "performance_indicators": {
    "primary_metrics": ["pace_min_per_km", "avg_hr", "distance_km"],
    "secondary_metrics": ["kcal_per_km", "cadence", "elevation_gain"],
    "benchmark_values": {
      "beginner": {"pace_min_per_km": 7.0, "distance_km": 3.0},
      "intermediate": {"pace_min_per_km": 6.0, "distance_km": 5.0},
      "advanced": {"pace_min_per_km": 5.0, "distance_km": 10.0}
    }
  },

  // ━━━ 6. KONTEXT & VARIANTEN ━━━
  "context": {
    "environment": ["outdoor", "indoor_treadmill"],
    "weather_sensitivity": "high",
    "equipment_required": ["running_shoes"],
    "location_types": ["road", "trail", "track"],
    "variants": [
      {
        "name": "intervall_lauf",
        "modifications": {
          "intensity_zones.focus": "schwellentraining",
          "minimum_requirements.avg_hr_min": 140
        }
      },
      {
        "name": "long_jog",
        "modifications": {
          "intensity_zones.focus": "grundlagenausdauer",
          "minimum_requirements.duration_min": 60
        }
      }
    ]
  },

  // ━━━ 7. SICHERHEIT & KONTRAINDIKATIONEN ━━━
  "safety": {
    "max_hr_warning": 180,
    "min_recovery_hr": 100,
    "contraindications": [
      "acute_injury_lower_body",
      "cardiovascular_episode_recent"
    ],
    "weather_limits": {
      "temp_celsius_min": -5,
      "temp_celsius_max": 32,
      "wind_speed_kmh_max": 40
    }
  },

  // ━━━ 8. KI-ANALYSE KONTEXT ━━━
  "ai_context": {
    "questions_to_ask": [
      "Wie fühlte sich dein Tempo an?",
      "Hattest du Atembeschwerden?",
      "Wie war die Regeneration danach?"
    ],
    "evaluation_focus": [
      "Pace-Entwicklung über Distanz",
      "Herzfrequenz-Stabilität",
      "Erholungspuls nach Training"
    ],
    "comparison_metrics": [
      "Tempo vs. letzte 4 Wochen",
      "Durchschnittspuls bei gleicher Distanz",
      "Subjektive Anstrengung (RPE) vs. objektive Daten"
    ]
  }
}
```

---

## Dynamische Bewertung: Wie das Profil genutzt wird

### 1. Mindestanforderungen-Check (Quality Gate)

**Funktion:** `evaluate_minimum_requirements(activity, profile)`

```python
def evaluate_minimum_requirements(activity: dict, profile: dict) -> dict:
    """
    Prüft ob Aktivität Mindestanforderungen erfüllt.

    Returns:
        {
            "passed": bool,
            "score": float,
            "failed_rules": [{"rule": str, "expected": val, "actual": val}],
            "recommendation": str
        }
    """
    requirements = profile['minimum_requirements']
    if not requirements['enabled']:
        return {"passed": True, "score": 1.0, "failed_rules": []}

    total_weight = 0
    passed_weight = 0
    failed_rules = []

    for rule_name, rule_config in requirements['rules'].items():
        weight = rule_config['weight']
        total_weight += weight

        actual = activity.get(rule_name)
        expected = rule_config['value']

        if actual is not None and actual >= expected:
            passed_weight += weight
        else:
            failed_rules.append({
                "rule": rule_name,
                "expected": expected,
                "actual": actual,
                "reason": rule_config['reason']
            })

    score = passed_weight / total_weight if total_weight > 0 else 1.0
    passed = score >= requirements['pass_threshold']

    recommendation = generate_recommendation(failed_rules, profile)

    return {
        "passed": passed,
        "score": round(score, 2),
        "failed_rules": failed_rules,
        "recommendation": recommendation
    }
```

### 2. Intensitäts-Bewertung (Zone Analysis)

**Funktion:** `evaluate_intensity_distribution(activity, profile)`

```python
def evaluate_intensity_distribution(activity: dict, profile: dict) -> dict:
    """
    Analysiert in welcher HF-Zone das Training stattfand.

    Returns:
        {
            "dominant_zone": str,
            "time_in_zones": {zone: minutes},
            "zone_quality": float (0-1),
            "recommendation": str
        }
    """
    zones = profile['intensity_zones']['zones']
    max_hr = activity.get('user_max_hr', 180)  # From user profile
    avg_hr = activity.get('avg_hr')

    if not avg_hr:
        return {"dominant_zone": "unknown", "zone_quality": 0}

    avg_hr_percent = (avg_hr / max_hr) * 100

    # Finde passende Zone
    dominant_zone = None
    for zone in zones:
        if zone['min_percent'] <= avg_hr_percent <= zone['max_percent']:
            dominant_zone = zone
            break

    if not dominant_zone:
        return {"dominant_zone": "out_of_range", "zone_quality": 0}

    # Prüfe ob Dauer passt zur Zone
    duration = activity.get('duration_min', 0)
    target_duration = dominant_zone['target_duration_min']

    duration_quality = min(duration / target_duration, 1.0)

    recommendation = f"Training in Zone '{dominant_zone['name']}' (Effekt: {dominant_zone['effect']}). "
    if duration < target_duration:
        recommendation += f"Für optimale Wirkung: {target_duration}min empfohlen."

    return {
        "dominant_zone": dominant_zone['name'],
        "zone_color": dominant_zone['color'],
        "zone_effect": dominant_zone['effect'],
        "avg_hr_percent": round(avg_hr_percent, 1),
        "duration_quality": round(duration_quality, 2),
        "recommendation": recommendation
    }
```

### 3. Trainingswirkung-Analyse (Abilities Development)

**Funktion:** `evaluate_training_effects(activity, profile)`

```python
def evaluate_training_effects(activity: dict, profile: dict) -> dict:
    """
    Berechnet welche Fähigkeiten durch diese Aktivität trainiert wurden.

    Returns:
        {
            "abilities_trained": [
                {"category": str, "ability": str, "intensity": int, "quality": float}
            ],
            "total_training_load": float
        }
    """
    effects = profile['training_effects']
    intensity_eval = evaluate_intensity_distribution(activity, profile)
    min_requirements_eval = evaluate_minimum_requirements(activity, profile)

    # Qualitätsfaktor basierend auf Mindestanforderungen
    quality_factor = min_requirements_eval['score']

    abilities_trained = []

    # Primary abilities mit voller Intensität
    for ability in effects['primary_abilities']:
        abilities_trained.append({
            "category": ability['category'],
            "ability": ability['ability'],
            "intensity": ability['intensity'],
            "quality": quality_factor,
            "contribution": ability['intensity'] * quality_factor
        })

    # Secondary abilities mit reduzierter Intensität
    for ability in effects['secondary_abilities']:
        abilities_trained.append({
            "category": ability['category'],
            "ability": ability['ability'],
            "intensity": ability['intensity'],
            "quality": quality_factor * 0.7,  # Sekundär = 70%
            "contribution": ability['intensity'] * quality_factor * 0.7
        })

    total_training_load = sum(a['contribution'] for a in abilities_trained)

    return {
        "abilities_trained": abilities_trained,
        "total_training_load": round(total_training_load, 2),
        "metabolic_focus": effects['metabolic_focus'],
        "muscle_groups": effects['muscle_groups']
    }
```

### 4. Periodisierungs-Check (Recovery & Frequency)

**Funktion:** `evaluate_periodization_compliance(activity, profile, recent_activities)`

```python
def evaluate_periodization_compliance(
    activity: dict,
    profile: dict,
    recent_activities: list
) -> dict:
    """
    Prüft ob Aktivität zu Periodisierungs-Empfehlungen passt.

    Returns:
        {
            "frequency_status": str,
            "recovery_adequate": bool,
            "warning": str | None
        }
    """
    periodization = profile['periodization']
    activity_date = activity['date']

    # Zähle gleiche Trainingstypen in letzter Woche
    same_type_count = sum(
        1 for a in recent_activities
        if a['training_type_id'] == activity['training_type_id']
        and days_between(a['date'], activity_date) <= 7
    )

    # Prüfe Erholungszeit
    last_same_type = next(
        (a for a in recent_activities
         if a['training_type_id'] == activity['training_type_id']),
        None
    )

    recovery_adequate = True
    warning = None

    if last_same_type:
        hours_since_last = hours_between(last_same_type['date'], activity_date)
        required_hours = periodization['recovery_requirement']['hours_before_same_type']

        if hours_since_last < required_hours:
            recovery_adequate = False
            warning = f"Zu wenig Erholung: {hours_since_last}h statt {required_hours}h empfohlen"

    # Frequenz-Status
    optimal_freq = periodization['recommended_frequency']['per_week_optimal']
    if same_type_count < optimal_freq:
        frequency_status = "under_optimal"
    elif same_type_count > periodization['recommended_frequency']['per_week_max']:
        frequency_status = "over_optimal"
        warning = "Übertraining-Risiko: Zu viele Einheiten diese Woche"
    else:
        frequency_status = "optimal"

    return {
        "frequency_status": frequency_status,
        "weekly_count": same_type_count,
        "recovery_adequate": recovery_adequate,
        "warning": warning
    }
```

### 5. Leistungsentwicklung (Performance Tracking)

**Funktion:** `evaluate_performance_development(activity, profile, historical_activities)`

```python
def evaluate_performance_development(
    activity: dict,
    profile: dict,
    historical_activities: list
) -> dict:
    """
    Vergleicht aktuelle Leistung mit Historie.

    Returns:
        {
            "trend": str,  # "improving" | "stable" | "declining"
            "metrics_comparison": {metric: {"current": val, "avg_4weeks": val, "change_percent": val}},
            "benchmark_level": str  # "beginner" | "intermediate" | "advanced"
        }
    """
    kpis = profile['performance_indicators']
    primary_metrics = kpis['primary_metrics']

    # Berechne 4-Wochen-Durchschnitte
    comparison = {}
    for metric in primary_metrics:
        current_value = activity.get(metric)
        if not current_value:
            continue

        historical_values = [
            a[metric] for a in historical_activities[-12:]  # Letzte 12 Einheiten
            if a.get(metric) is not None
        ]

        if historical_values:
            avg_historical = sum(historical_values) / len(historical_values)
            change_percent = ((current_value - avg_historical) / avg_historical) * 100

            comparison[metric] = {
                "current": current_value,
                "avg_4weeks": round(avg_historical, 2),
                "change_percent": round(change_percent, 1)
            }

    # Trend-Bewertung
    if all(c['change_percent'] > 5 for c in comparison.values()):
        trend = "improving"
    elif all(c['change_percent'] < -5 for c in comparison.values()):
        trend = "declining"
    else:
        trend = "stable"

    # Benchmark-Level ermitteln
    benchmarks = kpis['benchmark_values']
    benchmark_level = determine_benchmark_level(activity, benchmarks)

    return {
        "trend": trend,
        "metrics_comparison": comparison,
        "benchmark_level": benchmark_level
    }
```

---

## Dynamische Gesamt-Bewertung

**Master-Funktion:** `evaluate_activity(activity, profile, context)`

```python
def evaluate_activity(activity: dict, profile: dict, context: dict) -> dict:
    """
    Vollständige Bewertung einer Aktivität anhand des Trainingstyp-Profils.

    Args:
        activity: Die zu bewertende Aktivität
        profile: Das Trainingstyp-Profil
        context: {
            "recent_activities": [...],
            "historical_activities": [...],
            "user_profile": {...}
        }

    Returns:
        {
            "evaluated_at": ISO timestamp,
            "version": "1.0",
            "minimum_requirements": {...},
            "intensity_analysis": {...},
            "training_effects": {...},
            "periodization_check": {...},
            "performance_development": {...},
            "overall_score": float (0-1),
            "quality_label": str,  # "excellent" | "good" | "acceptable" | "poor"
            "recommendations": [str],
            "warnings": [str]
        }
    """

    results = {
        "evaluated_at": datetime.now().isoformat(),
        "version": "1.0",
        "minimum_requirements": evaluate_minimum_requirements(activity, profile),
        "intensity_analysis": evaluate_intensity_distribution(activity, profile),
        "training_effects": evaluate_training_effects(activity, profile),
        "periodization_check": evaluate_periodization_compliance(
            activity, profile, context['recent_activities']
        ),
        "performance_development": evaluate_performance_development(
            activity, profile, context['historical_activities']
        )
    }

    # Gesamt-Score berechnen (gewichtet)
    weights = {
        "minimum_requirements": 0.4,
        "intensity_analysis": 0.2,
        "periodization_check": 0.2,
        "performance_development": 0.2
    }

    overall_score = (
        results['minimum_requirements']['score'] * weights['minimum_requirements'] +
        results['intensity_analysis']['duration_quality'] * weights['intensity_analysis'] +
        (1.0 if results['periodization_check']['recovery_adequate'] else 0.5) * weights['periodization_check'] +
        (1.0 if results['performance_development']['trend'] == 'improving' else 0.7) * weights['performance_development']
    )

    # Quality Label
    if overall_score >= 0.9:
        quality_label = "excellent"
    elif overall_score >= 0.7:
        quality_label = "good"
    elif overall_score >= 0.5:
        quality_label = "acceptable"
    else:
        quality_label = "poor"

    # Recommendations sammeln
    recommendations = []
    warnings = []

    if not results['minimum_requirements']['passed']:
        for failed in results['minimum_requirements']['failed_rules']:
            recommendations.append(
                f"{failed['rule']}: {failed['reason']} (Ist: {failed['actual']}, Soll: {failed['expected']})"
            )

    if results['periodization_check']['warning']:
        warnings.append(results['periodization_check']['warning'])

    results.update({
        "overall_score": round(overall_score, 2),
        "quality_label": quality_label,
        "recommendations": recommendations,
        "warnings": warnings
    })

    return results
```

---

## DB-Schema (Erweitert)

```sql
-- Training Types: Vollständiges Profil
ALTER TABLE training_types ADD COLUMN profile JSONB DEFAULT NULL;

-- Activity Log: Evaluation Results
ALTER TABLE activity_log ADD COLUMN evaluation JSONB DEFAULT NULL;

-- Beispiel-Daten:
UPDATE training_types SET profile = '{...siehe oben...}'::jsonb
WHERE name_de = 'Laufen';
```

---

## User Interface: Aktivitäts-Detail-Ansicht

```
┌────────────────────────────────────────────────────────────────┐
│ 🏃 Laufen - 23. März 2026                                      │
├────────────────────────────────────────────────────────────────┤
│                                                                 │
│ ━━━ ZUSAMMENFASSUNG ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  │
│                                                                 │
│ Gesamtbewertung: ⭐⭐⭐⭐⭐ Exzellent (Score: 0.92)            │
│                                                                 │
│ 45 Minuten · 5.2 km · Ø 142 bpm (79% Max-HF) · 380 kcal      │
│                                                                 │
│ ━━━ MINDESTANFORDERUNGEN ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  │
│                                                                 │
│ ✅ Dauer: 45min (≥ 15min erforderlich)                        │
│ ✅ Ø Herzfrequenz: 142 bpm (≥ 100 bpm)                        │
│ ✅ Max. Herzfrequenz: 165 bpm (≥ 120 bpm)                     │
│ ✅ Distanz: 5.2 km (≥ 1.0 km)                                 │
│                                                                 │
│ ━━━ INTENSITÄTSANALYSE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  │
│                                                                 │
│ Trainingszone: Entwicklungsbereich (70-80% Max-HF)            │
│ Effekt: VO2max-Training, Laktattoleranz                        │
│                                                                 │
│ [████████████████████░░] 79% Max-HF                            │
│                                                                 │
│ Zeitverteilung:                                                 │
│ • Regenerativ (50-60%):      0 min                             │
│ • Grundlagenausdauer (60-70%): 8 min                           │
│ • Entwicklungsbereich (70-80%): 32 min ✅ Optimal             │
│ • Schwellentraining (80-90%):  5 min                           │
│                                                                 │
│ ━━━ TRAININGSWIRKUNG ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  │
│                                                                 │
│ Trainierte Fähigkeiten:                                        │
│ • Ausdauer (Konditionell):     ●●●●● (5/5) - Primärfokus      │
│ • Schnelligkeit (Konditionell): ●●○○○ (2/5) - Nebenfokus      │
│ • Rhythmus (Koordinativ):      ●●●○○ (3/5) - Sekundär         │
│ • Willenskraft (Psychisch):    ●●●●○ (4/5) - Sekundär         │
│                                                                 │
│ Gesamte Trainingsbelastung: 18.2 Punkte                       │
│                                                                 │
│ ━━━ PERIODISIERUNG ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  │
│                                                                 │
│ Frequenz diese Woche: 3 Einheiten ✅ Optimal (2-5 empfohlen)  │
│ Erholung seit letztem Lauf: 52 Stunden ✅ Ausreichend         │
│ Nächstes Training empfohlen: Frühestens in 48h                │
│                                                                 │
│ ━━━ LEISTUNGSENTWICKLUNG ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  │
│                                                                 │
│ Trend: ↗ Verbesserung                                          │
│                                                                 │
│ Pace: 8:39 min/km (Ø 4 Wochen: 9:15 min/km) +6.5% schneller  │
│ Ø HF: 142 bpm (Ø 4 Wochen: 148 bpm) -4% niedriger            │
│                                                                 │
│ Dein Level: Fortgeschritten (Intermediate)                    │
│                                                                 │
│ ━━━ EMPFEHLUNGEN ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  │
│                                                                 │
│ ✨ Exzellentes Training! Du trainierst im optimalen           │
│    Entwicklungsbereich für VO2max-Verbesserung.               │
│                                                                 │
│ 💡 Deine Pace verbessert sich stetig bei gleichzeitig         │
│    niedrigerer Herzfrequenz - klares Zeichen für bessere      │
│    Ausdauerkapazität.                                          │
│                                                                 │
│ 📅 Nächste Schritte:                                           │
│    • 1-2 Tage Regeneration                                     │
│    • Dann: Langer, langsamer Lauf (60-70% Max-HF, 60min)     │
│                                                                 │
└────────────────────────────────────────────────────────────────┘
```

---

## Implementierungs-Phasen

### Phase 1: Foundation (MVP)
1. DB-Migration: `profile` Spalte in training_types
2. DB-Migration: `evaluation` Spalte in activity_log
3. Backend: `evaluate_activity()` Master-Funktion
4. Backend: Evaluation beim INSERT/UPDATE

### Phase 2: Profile Editor (Admin-UI)
5. Admin-UI: Trainingstyp-Profil-Editor (JSON-basiert)
6. Admin-UI: Profile-Templates für Top 5 Trainingstypen
7. Admin-UI: Preview-Funktion (wie wird evaluiert?)

### Phase 3: User Experience
8. Frontend: Aktivitäts-Detail-Ansicht mit allen Bewertungen
9. Frontend: Badge-System (Excellent/Good/Acceptable/Poor)
10. Frontend: Trainingswirkungs-Visualisierung

### Phase 4: Advanced Features
11. KI-Integration: Nutze Evaluation-Daten für Prompts
12. Periodisierungs-Warnungen im Dashboard
13. Leistungsentwicklung-Charts
14. Historische Re-Evaluation (Batch-Job)

**Geschätzter Aufwand:** 12-16 Stunden (komplett)

---

## Offene Fragen

1. **Profil-Komplexität:** Alle Parameter von Anfang an oder iterativ erweitern?
2. **User-Anpassbarkeit:** Soll User eigene Profile erstellen können?
3. **Performance:** JSONB-Queries optimiert genug für große Datenmengen?
4. **UI-Komplexität:** Ist die Detail-Ansicht zu überladen?
5. **Backward Compatibility:** Was passiert mit Aktivitäten ohne Profil?

---

---

## Implementierungs-Status

### Phase 1: Foundation ✅ KOMPLETT (23.03.2026)

**Phase 1.1: Database & Core Engine** ✅
- ✅ Migration 013: training_parameters Tabelle (16 Standard-Parameter)
- ✅ Migration 014: training_types.profile + activity_log.evaluation + triggers
- ✅ rule_engine.py: RuleEvaluator mit 9 Operatoren
- ✅ rule_engine.py: IntensityZoneEvaluator für HF-Zonen
- ✅ rule_engine.py: TrainingEffectsEvaluator für Fähigkeiten
- ✅ profile_evaluator.py: TrainingProfileEvaluator (7 Dimensionen)
- ✅ evaluation_helper.py: Parameter-Loading + Context-Loading + Batch-Evaluation
- ✅ routers/evaluation.py: API-Endpoints für manuelle Evaluation
- ✅ Commit: 1b9cd6d

**Phase 1.2: Auto-Evaluation** ✅
- ✅ activity.py: create_activity() → Auto-Evaluation nach INSERT
- ✅ activity.py: update_activity() → Auto-Evaluation nach UPDATE
- ✅ activity.py: import_activity_csv() → Auto-Evaluation nach CSV-Import
- ✅ activity.py: bulk_categorize_activities() → Auto-Evaluation nach Bulk-Update
- ✅ Fehlerbehandlung mit try/except (verhindert Blockierung bei Evaluation-Fehlern)
- ✅ Commit: e119537

**Backend Implementation:** 100% komplett
- Parameter-Registry: extensibel via SQL
- Regel-System: flexibel, unterstützt >= und <= (Laufen vs. Meditation)
- 7 Dimensionen: Minimum Requirements, Intensity Zones, Training Effects, Periodization, Performance, Safety, AI Context
- Evaluation-Results in activity_log.evaluation gespeichert

**Getestet:** Syntax-Check bestanden (py_compile)

### Phase 2: Admin-UI 🔲 Ausstehend

**Aufgaben:**
- Admin-UI: Parameter-Registry-Verwaltung (CRUD)
- Admin-UI: Trainingstyp-Profil-Editor (JSON-Editor mit Syntax-Highlighting)
- Admin-UI: Profile-Templates für Top 5 Trainingstypen (Laufen, Radfahren, Schwimmen, Krafttraining, Meditation)
- Admin-UI: Preview-Funktion (Test-Evaluation mit Beispiel-Aktivität)
- Validation: Profil-Schema-Validator

**Geschätzter Aufwand:** 4-6 Stunden

### Phase 3: User-UI 🔲 Ausstehend

**Aufgaben:**
- Frontend: ActivityDetailPage mit vollständiger Evaluation-Anzeige
- Frontend: Quality Badges (excellent/good/acceptable/poor) in Listen
- Frontend: Filter nach Quality Label
- Frontend: Trainingswirkungs-Visualisierung (Fähigkeiten-Übersicht)
- Frontend: Dashboard-Stats (Durchschnitt Quality Score)

**Geschätzter Aufwand:** 4-6 Stunden

### Phase 4: Advanced Features 🔲 Future

**Optional:**
- KI-Integration: Nutze Evaluation-Daten in AI-Prompts
- Periodisierungs-Warnungen im Dashboard
- Leistungsentwicklung-Charts
- Historische Re-Evaluation (Batch-Job über Admin-Panel)

**Was denkst du zu diesem erweiterten Ansatz?**
