name: Build & Deploy Pluriwave

on:
  push:
    branches: [main]

env:
  PATH: /opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
  ANDROID_HOME: /Users/freetlab/Library/Android/sdk

jobs:
  analizar:
    name: Análisis de código
    runs-on: [self-hosted, macos, arm64, flutter]
    steps:
      - uses: actions/checkout@v4
      - name: Obtener dependencias
        run: flutter pub get
      #- name: Generar l10n
      #  run: flutter gen-l10n
      - name: Analizar código
        run: flutter analyze --no-fatal-infos --no-fatal-warnings

  build:
    name: Build APK + AAB release
    runs-on: [self-hosted, macos, arm64, flutter]
    needs: analizar
    if: ${{ gitea.ref == 'refs/heads/main' }}
    steps:
      - uses: actions/checkout@v4

      - name: Bump versión patch + commit
        run: |
          git config user.name "ShanaiaBot"
          git config user.email "shanaia@freetimelab.es"
          CURRENT=$(grep '^version:' pubspec.yaml | awk '{print $2}')
          SEMVER=$(echo $CURRENT | cut -d'+' -f1)
          BUILD=$(echo $CURRENT | cut -d'+' -f2)
          MAJOR=$(echo $SEMVER | cut -d. -f1)
          MINOR=$(echo $SEMVER | cut -d. -f2)
          PATCH=$(echo $SEMVER | cut -d. -f3)
          NEW_PATCH=$((PATCH + 1))
          NEW_BUILD=$((BUILD + 1))
          NEW_VERSION="${MAJOR}.${MINOR}.${NEW_PATCH}+${NEW_BUILD}"
          sed -i '' "s/^version: .*/version: ${NEW_VERSION}/" pubspec.yaml
          git add pubspec.yaml
          git commit -m "chore: bump version to ${NEW_VERSION} [ci skip]"
          git push origin main
          echo "NEW_SEMVER=${MAJOR}.${MINOR}.${NEW_PATCH}" >> $GITHUB_ENV

      - name: Extraer versión
        id: version
        run: |
          VERSION=$(grep '^version:' pubspec.yaml | awk '{print $2}' | cut -d'+' -f1)
          COMMIT=$(git rev-parse --short HEAD)
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "commit=$COMMIT" >> $GITHUB_OUTPUT

      - name: Obtener dependencias
        run: flutter pub get

      #- name: Generar l10n
      #  run: flutter gen-l10n

      - name: Build APK release
        run: flutter build apk --release

      - name: Build AAB release
        run: flutter build appbundle --release

      - name: Publicar en ftl-builds (Zimaboard)
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          APK_NOMBRE="pluriwave-v${VERSION}.apk"
          AAB_NOMBRE="pluriwave-v${VERSION}.aab"
          DESTINO="/opt/ftl-builds/builds/pluriwave/v${VERSION}"
          SSH_KEY="/Users/freetlab/.openclaw/workspace/.secure/zimaboard_ed25519"

          ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no ShanaiaBot@192.168.0.33 "mkdir -p ${DESTINO}"
          scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \
            build/app/outputs/flutter-apk/app-release.apk \
            "ShanaiaBot@192.168.0.33:${DESTINO}/${APK_NOMBRE}"
          scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \
            build/app/outputs/bundle/release/app-release.aab \
            "ShanaiaBot@192.168.0.33:${DESTINO}/${AAB_NOMBRE}"
          echo "✅ APK: builds.freetimelab.es → pluriwave → v${VERSION}"
          echo "✅ AAB: builds.freetimelab.es → pluriwave → v${VERSION}"

      - name: Notificar Telegram
        if: always()
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          COMMIT="${{ steps.version.outputs.commit }}"
          BOT_TOKEN=$(plutil -extract 'EnvironmentVariables:TELEGRAM_BOT_TOKEN' raw /Users/freetlab/Library/LaunchAgents/ai.openclaw.gateway.plist 2>/dev/null || echo "")
          if [ -z "$BOT_TOKEN" ]; then exit 0; fi
          if [ "${{ job.status }}" = "success" ]; then
            MSG="✅ *Pluriwave* v${VERSION} build OK · ${COMMIT}%0AAPK + AAB en builds.freetimelab.es"
          else
            MSG="❌ *Pluriwave* v${VERSION} build FAILED · ${COMMIT}"
          fi
          curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \
            -d "chat_id=221721467" -d "parse_mode=Markdown" -d "text=${MSG}" || true
