name: Vendoo CI

on:
  push:
    branches: [main, develop, 'feature/**', 'release/**', 'hotfix/**']
  pull_request:
    branches: [main, develop]
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: vendoo-ci-${{ github.ref }}
  cancel-in-progress: true

jobs:
  quality:
    name: Syntax, Sicherheit und Release-Gates
    runs-on: ubuntu-latest
    timeout-minutes: 25
    steps:
      - name: Repository auschecken
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Node.js 22 aktivieren
        uses: actions/setup-node@v4
        with:
          node-version: '22.x'
          cache: npm

      - name: Abhängigkeiten reproduzierbar installieren
        run: npm ci

      - name: Git-Sicherheitsgate
        run: npm run verify:git

      - name: Git-Sicherheitsgate Regressionstest
        run: npm run verify:git-regression

      - name: Git-Staging-Filter Regressionstest
        run: npm run verify:git-staging

      - name: Release-Manifest und Paketvertrag prüfen
        run: npm run verify:release-manifest

      - name: Git-Ignore-Grenzen für Quell- und Runtimeordner prüfen
        run: npm run verify:ignore-boundaries

      - name: Syntaxprüfung
        run: npm run check

      - name: PowerShell-Regressionen statisch prüfen
        run: npm run verify:powershell-static

      - name: Updater-3.4-Lifecycle und Startkette prüfen
        run: npm run verify:updater-start-chain && npm run verify:updater-lifecycle

      - name: Produktiven Source-Root und Archivgrenzen prüfen
        run: npm run verify:source-boundaries

      - name: ESM-Exportverträge prüfen
        run: npm run verify:esm-exports

      - name: FLUX-Loop-Hotfix prüfen
        run: npm run verify:flux-loop

      - name: Vollständigen Modul-Capability-Graph prüfen
        run: npm run verify:capabilities

      - name: Coolify-Deployment und Web-Updates prüfen
        run: npm run verify:coolify

      - name: Initial deaktivierte Module prüfen
        run: npm run verify:initial-modules

      - name: Plattformarchitektur und Design Tokens prüfen
        run: npm run verify:architecture

      - name: Theme Manager, Accessibility und Komponenten-Tokens prüfen
        run: npm run verify:themes

      - name: Security, Secrets und Observability prüfen
        run: npm run verify:security

      - name: Auth, Benutzer, Sitzungen und Einstellungen prüfen
        run: npm run verify:identity

      - name: Artikel, Lager und Medien prüfen
        run: npm run verify:catalog

      - name: Modulmanager, Pakete und Aktivierungsgrenzen prüfen
        run: npm run verify:modules

      - name: Deployment-Gate
        run: npm run verify:deployment

      - name: Persistenten Konfigurationsspeicher prüfen
        run: npm run verify:config

      - name: Geführte Shell-Installer simulieren
        run: npm run verify:installer-shell

      - name: Datenbankmigrationen prüfen
        run: npm run verify:db

      - name: Docker-Compose-Dateien validieren
        run: |
          cp .env.example .env
          python - <<'PY'
          from pathlib import Path
          p=Path('.env')
          s=p.read_text()
          s=s.replace('VENDOO_SETUP_TOKEN=', 'VENDOO_SETUP_TOKEN=ci-only-not-a-production-secret-1234567890')
          s=s.replace('VENDOO_DOMAIN=', 'VENDOO_DOMAIN=vendoo.example.invalid')
          p.write_text(s)
          PY
          docker compose -f compose.yaml config -q
          docker compose -f compose.yaml -f compose.bind-mounts.example.yaml config -q
          docker compose -f compose.vps.yaml config -q
          rm -f .env

      - name: Docker-Image testweise bauen
        run: docker build --pull --tag vendoo:ci .

  windows-release-contract:
    name: Windows – vollständiger Releasevertrag
    runs-on: windows-latest
    timeout-minutes: 35
    steps:
      - name: Repository auschecken
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Node.js 22 aktivieren
        uses: actions/setup-node@v4
        with:
          node-version: '22.x'
          cache: npm

      - name: Abhängigkeiten reproduzierbar installieren
        run: npm ci

      - name: Alle PowerShell-Dateien mit Windows PowerShell 5.1 parsen
        shell: powershell
        run: .\tools\verify-powershell-parser.ps1 -ReportPath "$env:RUNNER_TEMP\powershell-parser-diagnostics.txt"

      - name: Parserdiagnose bei Fehler sichern
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: powershell-parser-diagnostics-${{ github.event.pull_request.head.sha || github.sha }}
          path: ${{ runner.temp }}/powershell-parser-diagnostics.txt
          if-no-files-found: error
          retention-days: 14

      - name: Vollständigen Vendoo-Releasevertrag unter Windows ausführen
        shell: pwsh
        run: npm run verify:all

  package-after-acceptance:
    name: Updater-3.4-Paket nach Abnahme
    needs: [quality, windows-release-contract]
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - name: Exakten geprüften Head auschecken
        uses: actions/checkout@v6
        with:
          ref: ${{ github.event.pull_request.head.sha || github.sha }}
          fetch-depth: 0

      - name: Node.js 22 aktivieren
        uses: actions/setup-node@v4
        with:
          node-version: '22.x'
          cache: npm

      - name: Abhängigkeiten reproduzierbar installieren
        run: npm ci

      - name: main für den Provenienzvergleich aktualisieren
        run: git fetch origin main:refs/remotes/origin/main

      - name: Reproduzierbares Root-Manifest bestätigen
        shell: bash
        run: |
          node tools/generate-release-manifest.mjs .
          git diff --exit-code -- release-manifest.json

      - name: Paket mit unveränderlicher Provenienz erzeugen
        env:
          VENDOO_SOURCE_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
        run: node tools/build-release.mjs

      - name: Paketmanifest und SHA-256 prüfen
        shell: bash
        run: |
          set -euo pipefail
          release_name="$(tr -d '\r\n' < release-output/RELEASE_NAME.txt)"
          package_dir="release-output/${release_name}"
          node --input-type=module - "$package_dir" <<'NODE'
          import { readAndValidateManifest } from './tools/release-manifest-lib.mjs';
          const packageDir = process.argv[2];
          const manifest = readAndValidateManifest(packageDir);
          if (manifest.schema !== 'vendoo-release-package-v2') throw new Error(`Unerwartetes Paketschema: ${manifest.schema}`);
          if (manifest.updaterVersion !== '3.4.0') throw new Error(`Unerwartete Updater-Version: ${manifest.updaterVersion}`);
          if (manifest.targetVersion !== '1.43.0') throw new Error(`Unerwartete Zielversion: ${manifest.targetVersion}`);
          console.log(`Paket validiert: ${manifest.targetVersion}, Updater ${manifest.updaterVersion}, Payload ${manifest.payloadHash}`);
          NODE
          archive="release-output/${release_name}.zip"
          python tools/build-deterministic-zip.py "$package_dir" "$archive"
          first_hash="$(sha256sum "$archive" | awk '{print $1}')"
          python tools/build-deterministic-zip.py "$package_dir" "$archive"
          second_hash="$(sha256sum "$archive" | awk '{print $1}')"
          if [[ "$first_hash" != "$second_hash" ]]; then
            echo "Der ZIP-Build ist nicht byte-reproduzierbar." >&2
            exit 1
          fi
          python -m zipfile -t "$archive"
          (
            cd release-output
            sha256sum "${release_name}.zip" > "${release_name}.zip.sha256"
            sha256sum --check "${release_name}.zip.sha256"
          )

      - name: Abgenommenes Paket als CI-Artefakt bereitstellen
        uses: actions/upload-artifact@v4
        with:
          name: vendoo-1.43.0-updater-3.4-${{ github.event.pull_request.head.sha || github.sha }}
          path: |
            release-output/*.zip
            release-output/*.zip.sha256
          if-no-files-found: error
          retention-days: 14
