name: Guidelines Validation

on:
  push:
    paths:
      - '.junie/**/*.md'
      - '.junie/**/*.json'
      - '.junie/scripts/**'
  pull_request:
    paths:
      - '.junie/**/*.md'
      - '.junie/**/*.json'
      - '.junie/scripts/**'

jobs:
  validate-guidelines:
    runs-on: ubuntu-latest
    name: Validate Guidelines Structure and Links

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Setup Python for YAML validation
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install Required Tools
        run: |
          sudo apt-get update
          sudo apt-get install -y jq yamllint curl
          pip install pyyaml jsonschema

      - name: Validate YAML Headers in Guidelines
        run: |
          echo "🔍 Validiere YAML-Header in Guidelines..."
          exit_code=0
          find .junie/guidelines -name "*.md" -not -path "*/_archived/*" | while read file; do
            echo "  Prüfe: $(basename $file)"
            # YAML-Header extrahieren (zwischen ersten beiden --- Zeilen)
            sed -n '/^---$/,/^---$/p' "$file" | head -n -1 | tail -n +2 > temp.yaml
            if [[ -s temp.yaml ]]; then
              # Python-basierte YAML-Validierung (robuster als yamllint)
              python3 -c "import yaml, sys; yaml.safe_load(open('temp.yaml', 'r')); print('  ✅ YAML-Syntax OK')" || {
                echo "❌ YAML-Syntax-Fehler in $file"
                exit_code=1
              }
            else
              echo "  ⚠️  Kein YAML-Header in $file"
            fi
            rm -f temp.yaml
          done
          if [[ $exit_code -ne 0 ]]; then
            exit 1
          fi

      - name: Validate Cross-References and Links
        run: |
          echo "🔗 Validiere Cross-Referenzen und Links..."
          chmod +x .junie/scripts/validate-links.sh
          ./.junie/scripts/validate-links.sh

      - name: Check Versions Consistency
        run: |
          echo "📊 Prüfe Versions-Konsistenz..."
          # Alle last_updated Daten sammeln und auf Konsistenz prüfen
          echo "Aktuelle Versions-Verteilung:"
          find .junie/guidelines -name "*.md" -not -path "*/_archived/*" -exec grep -H "last_updated:" {} \; | \
          cut -d'"' -f2 | sort | uniq -c | sort -rn

          # Überprüfe guideline_type Konsistenz
          echo -e "\nGuideline-Types:"
          find .junie/guidelines -name "*.md" -not -path "*/_archived/*" -exec grep -H "guideline_type:" {} \; | \
          cut -d'"' -f2 | sort | uniq -c | sort -rn

      - name: Validate Template Structure and Metadata
        run: |
          echo "📋 Prüfe Template-Konsistenz und Metadaten..."
          exit_code=0
          find .junie/guidelines -name "*.md" -not -path "*/_archived/*" -not -name "README.md" | while read file; do
            echo "  Validiere: $(basename $file)"

            # Prüfe erforderliche YAML-Felder
            if ! grep -q "guideline_type:" "$file"; then
              echo "  ❌ Fehlt guideline_type in $file"
              exit_code=1
            fi
            if ! grep -q "ai_context:" "$file"; then
              echo "  ❌ Fehlt ai_context in $file"
              exit_code=1
            fi
            if ! grep -q "last_updated:" "$file"; then
              echo "  ❌ Fehlt last_updated in $file"
              exit_code=1
            fi

            echo "  ✅ Metadaten komplett"
          done
          if [[ $exit_code -ne 0 ]]; then
            exit 1
          fi

      - name: Validate JSON Configuration Files
        run: |
          echo "🔧 Validiere JSON-Konfigurationsdateien..."
          for json_file in .junie/guidelines/_meta/*.json; do
            if [[ -f "$json_file" ]]; then
              echo "  Prüfe: $(basename $json_file)"
              jq empty "$json_file" || {
                echo "❌ JSON-Syntax-Fehler in $json_file"
                exit 1
              }
              echo "  ✅ $(basename $json_file) - JSON-Syntax OK"
            fi
          done

      - name: Check Script Executability and Permissions
        run: |
          echo "⚙️  Prüfe Script-Berechtigungen..."
          for script in .junie/scripts/*.sh; do
            if [[ -f "$script" ]]; then
              echo "  Prüfe: $(basename $script)"
              if [[ -x "$script" ]]; then
                echo "  ✅ $(basename $script) - Ausführbar"
              else
                echo "  ❌ $(basename $script) - Nicht ausführbar"
                exit 1
              fi
            fi
          done

      - name: Generate Validation Report
        if: always()
        run: |
          echo "📈 Erstelle Validierungs-Report..."
          cat > guidelines-validation-report.md << 'EOF'
          # Guidelines Validation Report

          **Datum:** $(date)
          **Commit:** ${{ github.sha }}
          **Branch:** ${{ github.ref_name }}

          ## Zusammenfassung
          - ✅ YAML-Syntax validiert
          - ✅ Cross-Referenzen geprüft
          - ✅ Versions-Konsistenz überprüft
          - ✅ Template-Struktur validiert
          - ✅ JSON-Konfiguration validiert
          - ✅ Script-Berechtigungen geprüft

          ## Statistiken
          - **Aktive Guidelines:** $(find .junie/guidelines -name "*.md" -not -path "*/_archived/*" | wc -l)
          - **Archivierte Guidelines:** $(find .junie/guidelines/_archived -name "*.md" 2>/dev/null | wc -l)
          - **Templates verfügbar:** $(find .junie/guidelines/_templates -name "*.md" 2>/dev/null | wc -l)
          - **Validierungs-Scripts:** $(find .junie/scripts -name "*.sh" 2>/dev/null | wc -l)

          ## Letzte Änderungen
          ```
          $(git log --oneline -n 5 -- .junie/)
          ```
          EOF

      - name: Comment PR with Validation Results
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            if (fs.existsSync('guidelines-validation-report.md')) {
              const report = fs.readFileSync('guidelines-validation-report.md', 'utf8');
              github.rest.issues.createComment({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body: '## 📋 Guidelines Validation Report\n\n' + report
              });
            }

  advanced-link-check:
    runs-on: ubuntu-latest
    name: Advanced Link and Structure Validation
    needs: validate-guidelines

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Setup Node.js for markdown-link-check
        uses: actions/setup-node@v4
        with:
          node-version: '18'

      - name: Install Link Checker
        run: |
          npm install -g markdown-link-check@3.11.2

      - name: Create Link Check Configuration
        run: |
          cat > .junie/link-check-config.json << 'EOF'
          {
            "ignorePatterns": [
              {
                "pattern": "^http://localhost"
              },
              {
                "pattern": "^https://localhost"
              },
              {
                "pattern": "^http://127.0.0.1"
              }
            ],
            "replacementPatterns": [],
            "httpHeaders": [],
            "timeout": "10s",
            "retryOn429": true,
            "retryCount": 3,
            "fallbackRetryDelay": "30s",
            "aliveStatusCodes": [200, 206]
          }
          EOF

      - name: Check Internal Markdown Links
        run: |
          echo "🔍 Erweiterte Link-Validierung..."
          exit_code=0
          find .junie/guidelines -name "*.md" | while read file; do
            echo "Prüfe Links in: $(basename $file)"
            if ! markdown-link-check "$file" --config .junie/link-check-config.json --quiet; then
              echo "❌ Link-Fehler in $file"
              exit_code=1
            else
              echo "✅ Links OK in $(basename $file)"
            fi
          done
          if [[ $exit_code -ne 0 ]]; then
            echo "❌ Link-Validierung fehlgeschlagen"
            exit 1
          fi
          echo "✅ Alle Links validiert"
