# Woodpecker CI Auto-Fix Pipeline
# Automatische Reparatur fehlgeschlagener Tests
#
# Laeuft taeglich um 2:00 Uhr nachts
# Analysiert offene Backlog-Items und versucht automatische Fixes

when:
  - event: cron
    cron: "0 2 * * *"  # Taeglich um 2:00 Uhr

clone:
  git:
    image: woodpeckerci/plugin-git
    settings:
      depth: 1
    extra_hosts:
      - macmini:192.168.178.100

steps:
  # ========================================
  # 1. Fetch Failed Tests from Backlog
  # ========================================

  fetch-backlog:
    image: curlimages/curl:latest
    commands:
      - |
        curl -s "http://backend:8000/api/tests/backlog?status=open&priority=critical" \
          -o backlog-critical.json
        curl -s "http://backend:8000/api/tests/backlog?status=open&priority=high" \
          -o backlog-high.json
      - echo "=== Kritische Tests ==="
      - cat backlog-critical.json | head -50
      - echo "=== Hohe Prioritaet ==="
      - cat backlog-high.json | head -50

  # ========================================
  # 2. Analyze and Classify Errors
  # ========================================

  analyze-errors:
    image: python:3.12-slim
    commands:
      - pip install --quiet jq-py
      - |
        python3 << 'EOF'
        import json
        import os

        def classify_error(error_type, error_msg):
            """Klassifiziert Fehler nach Auto-Fix-Potential"""
            auto_fixable = {
                'nil_pointer': 'high',
                'import_error': 'high',
                'undefined_variable': 'medium',
                'type_error': 'medium',
                'assertion': 'low',
                'timeout': 'low',
                'logic_error': 'manual'
            }
            return auto_fixable.get(error_type, 'manual')

        # Lade Backlog
        try:
            with open('backlog-critical.json') as f:
                critical = json.load(f)
            with open('backlog-high.json') as f:
                high = json.load(f)
        except:
            print("Keine Backlog-Daten gefunden")
            exit(0)

        all_items = critical.get('items', []) + high.get('items', [])

        auto_fix_candidates = []
        for item in all_items:
            fix_potential = classify_error(
                item.get('error_type', 'unknown'),
                item.get('error_message', '')
            )
            if fix_potential in ['high', 'medium']:
                auto_fix_candidates.append({
                    'id': item.get('id'),
                    'test_name': item.get('test_name'),
                    'error_type': item.get('error_type'),
                    'fix_potential': fix_potential
                })

        print(f"Auto-Fix Kandidaten: {len(auto_fix_candidates)}")
        with open('auto-fix-candidates.json', 'w') as f:
            json.dump(auto_fix_candidates, f, indent=2)
        EOF
    depends_on:
      - fetch-backlog

  # ========================================
  # 3. Generate Fix Suggestions (Placeholder)
  # ========================================

  generate-fixes:
    image: python:3.12-slim
    commands:
      - |
        echo "Auto-Fix Generation ist in Phase 4 geplant"
        echo "Aktuell werden nur Vorschlaege generiert"

        # Hier wuerde Claude API oder anderer LLM aufgerufen werden
        # python3 scripts/auto-fix-agent.py auto-fix-candidates.json

        echo "Fix-Vorschlaege wuerden hier generiert werden"
    depends_on:
      - analyze-errors

  # ========================================
  # 4. Report Results
  # ========================================

  report-results:
    image: curlimages/curl:latest
    commands:
      - |
        curl -X POST "http://backend:8000/api/tests/auto-fix/report" \
          -H "Content-Type: application/json" \
          -d "{
            \"run_date\": \"$(date -Iseconds)\",
            \"candidates_found\": $(cat auto-fix-candidates.json | wc -l),
            \"fixes_attempted\": 0,
            \"fixes_successful\": 0,
            \"status\": \"analysis_only\"
          }" || true
    when:
      status: [success, failure]
