definitions:
  steps:
    - step: &build-step
        name: SonarQube analysis
        script:
          - pipe: sonarsource/sonarqube-scan:3.0.2
            variables:
              SONAR_HOST_URL: ${SONAR_HOST_URL}
              SONAR_TOKEN: ${SONAR_TOKEN}
  caches:
    sonar: ~/.sonar

clone:
  depth: full

pipelines:
  branches:
    '{main}':
      - step: *build-step

image: ghcr.io/cirruslabs/flutter:stable

definitions:
  caches:
    sonar: ~/.sonar
    flutter: ~/.pub-cache
    gradle: ~/.gradle/caches
    cocoapods: ~/Library/Caches/CocoaPods  # Changed from ~/.cocoapods
    bundler: ios/vendor/bundle

  steps:
    - step: &build-android-diagnostic
        name: Build Android AAB (Diagnostic)
        size: 2x
        caches:
          - flutter
          - gradle
        script:
          - echo "========================================"
          - echo "DIAGNOSTIC MODE - DETAILED LOGGING"
          - echo "========================================"
          - echo "Building Android for $BITBUCKET_BRANCH"
          - echo "Checking default Java version..."
          - java -version 2>&1 || echo "No default Java"
          - which java || echo "Java not in PATH"
          - echo "Installing JDK 21..."
          - apt-get update && apt-get install -y openjdk-21-jdk
          - echo "Setting JAVA_HOME..."
          - export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-$(dpkg --print-architecture)
          - export PATH="$JAVA_HOME/bin:$PATH"
          - echo "========================================"
          - echo "INSTALLED JAVA VERSIONS:"
          - ls -la /usr/lib/jvm/
          - echo "========================================"
          - echo "CURRENT JAVA VERSION (after setting JAVA_HOME):"
          - java -version 2>&1
          - javac -version 2>&1
          - echo "JAVA_HOME is $JAVA_HOME"
          - echo "PATH is $PATH"
          - echo "Which java:"
          - which java
          - echo "Cleaning up Gradle..."
          - pkill -9 java || echo "No Java processes to kill"
          - rm -rf ~/.gradle/daemon || echo "No daemon to remove"
          - rm -rf ~/.gradle/caches || echo "No caches to remove"
          - cd android && (./gradlew --stop || echo "Gradle stop failed") && cd ..
          - echo "========================================"
          - echo "CONFIGURING GRADLE FOR JDK 21"
          - echo "========================================"
          - echo "org.gradle.java.home=$JAVA_HOME" >> android/gradle.properties
          - echo "java.home=$JAVA_HOME" >> android/local.properties
          - export GRADLE_OPTS="-Dorg.gradle.java.home=$JAVA_HOME -Dorg.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=768m"
          - echo "GRADLE_OPTS is $GRADLE_OPTS"
          - echo "========================================"
          - echo "GRADLE.PROPERTIES CONTENT:"
          - cat android/gradle.properties || echo "No gradle.properties"
          - echo "========================================"
          - echo "Decoding keystore..."
          - echo $ANDROID_KEYSTORE_BASE64 | tr -d '\n' | base64 -d > android/app/upload-keystore.jks
          - echo "========================================"
          - echo "KEYSTORE FILE INFO:"
          - ls -lh android/app/upload-keystore.jks
          - file android/app/upload-keystore.jks || echo "file command not available"
          - echo "========================================"
          - echo "TESTING KEYSTORE WITH JDK 21:"
          - $JAVA_HOME/bin/keytool -list -v -keystore android/app/upload-keystore.jks -storepass $ANDROID_STORE_PASSWORD 2>&1 | head -30 || echo "KEYSTORE READ FAILED WITH JDK 21!"
          - echo "========================================"
          - echo "TESTING KEYSTORE WITH DEFAULT KEYTOOL:"
          - keytool -list -v -keystore android/app/upload-keystore.jks -storepass $ANDROID_STORE_PASSWORD 2>&1 | head -30 || echo "KEYSTORE READ FAILED WITH DEFAULT!"
          - echo "========================================"
          - |
            cat > android/key.properties << EOF
            storePassword=$ANDROID_STORE_PASSWORD
            keyPassword=$ANDROID_KEY_PASSWORD
            keyAlias=$ANDROID_KEY_ALIAS
            storeFile=upload-keystore.jks
            EOF
          - echo "KEY.PROPERTIES CREATED (passwords hidden)"
          - sed 's/Password=.*/Password=***HIDDEN***/g' android/key.properties
          - echo "========================================"
          - flutter pub get
          - echo "GRADLE VERSION:"
          - cd android && ./gradlew --version && cd ..
          - echo "========================================"
          - echo "STARTING FLUTTER BUILD..."
          - flutter build appbundle --release --verbose --dart-define=SUPABASE_URL=$SUPABASE_URL --dart-define=SUPABASE_ANON_KEY=$SUPABASE_ANON_KEY 2>&1 | tee build.log || echo "BUILD FAILED - Check logs above"
          - echo "========================================="
          - echo "LAST 50 LINES OF BUILD OUTPUT:"
          - tail -50 build.log || echo "No build log"
          - echo "========================================"
          - echo "CHECKING FOR AAB FILE:"
          - ls -lh build/app/outputs/bundle/release/ || echo "No AAB created"
        artifacts:
          - build/app/outputs/bundle/release/app-release.aab
          - build.log

    - step: &build-android
        name: Build Android AAB
        size: 2x
        caches:
          - flutter
          - gradle
        script:
          - echo "Building Android for $BITBUCKET_BRANCH"
          - apt-get update && apt-get install -y openjdk-21-jdk
          - export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-$(dpkg --print-architecture)
          - export PATH="$JAVA_HOME/bin:$PATH"
          - java -version
          - pkill -9 java || true
          - rm -rf ~/.gradle/daemon || true
          - cd android && (./gradlew --stop || true) && cd ..
          - echo "org.gradle.java.home=$JAVA_HOME" >> android/gradle.properties
          - echo "java.home=$JAVA_HOME" >> android/local.properties
          - export GRADLE_OPTS="-Dorg.gradle.java.home=$JAVA_HOME -Dorg.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=768m"
          - echo $ANDROID_KEYSTORE_BASE64 | tr -d '\n' | base64 -d > android/app/upload-keystore.jks
          - |
            cat > android/key.properties << EOF
            storePassword=$ANDROID_STORE_PASSWORD
            keyPassword=$ANDROID_KEY_PASSWORD
            keyAlias=$ANDROID_KEY_ALIAS
            storeFile=upload-keystore.jks
            EOF
          - flutter pub get
          - export VERSION_CODE=$((84 + BITBUCKET_BUILD_NUMBER))
          - echo "Using version code $VERSION_CODE"
          - flutter build appbundle --release --build-number=$VERSION_CODE --dart-define=SUPABASE_URL=$SUPABASE_URL --dart-define=SUPABASE_ANON_KEY=$SUPABASE_ANON_KEY
          - ls -lh build/app/outputs/bundle/release/
        artifacts:
          - build/app/outputs/bundle/release/app-release.aab

    - step: &deploy-android-internal
        name: Deploy to Play Store (Internal Track)
        image: ruby:3.2
        script:
          - gem install bundler -NV
          - ls -lh build/app/outputs/bundle/release/
          - echo "$ANDROID_PLAYSTORE_JSON_BASE64" | tr -d '\n' | base64 -d > android/playstore-credentials.json
          - test -s android/playstore-credentials.json || (echo "ERROR playstore-credentials.json missing or empty" && exit 1)
          - head -c 1 android/playstore-credentials.json | grep -q "{" || (echo "ERROR playstore-credentials.json is not valid JSON" && exit 1)
          - cd android
          - bundle install
          - bundle exec fastlane internal

    # iOS: requires self-hosted macOS runner (Repository/Workspace Settings → Runners → Add macOS runner with label "macos").
    # Note: size is not supported on self-hosted runners; omit it for runs-on: self.hosted.
    - step: &build-ios
        name: Build iOS
        runs-on:
          - self.hosted
          - macos
        caches:
          - flutter
          - cocoapods
        script:
          - echo "Building iOS for $BITBUCKET_BRANCH"
          - flutter pub get
          - flutter build ios --release --no-codesign --dart-define=SUPABASE_URL=$SUPABASE_URL --dart-define=SUPABASE_ANON_KEY=$SUPABASE_ANON_KEY
          - ls -lh build/ios/iphoneos/Runner.app || true
        artifacts:
          - build/ios/iphoneos/Runner.app

    - step: &deploy-ios-testflight
        name: Deploy to TestFlight (Internal)
        runs-on:
          - self.hosted
          - macos
        caches:
          - flutter
          - cocoapods
          - bundler
        script:
          - gem install bundler -NV
          - cd ios
          - bundle install
          - cd ..
          - flutter pub get
          - mkdir -p ~/.private_keys
          - echo "$IOS_APP_STORE_CONNECT_API_KEY_BASE64" | tr -d '\n' | base64 -d > ~/.private_keys/AuthKey.p8
          - chmod 600 ~/.private_keys/AuthKey.p8
          - cd ios
          - gem pristine ffi 2>/dev/null || true
          - bundle exec pod install
          - bundle exec fastlane beta
        artifacts:
          - ios/*.ipa

pipelines:
  default:
    - step:
        name: Pub get
        caches:
          - flutter
        script:
          - flutter pub get

  branches:
    # develop: Android + iOS. iOS steps require a self-hosted macOS runner with labels self.hosted, macos (see BITBUCKET_MACOS_RUNNER_SETUP.md).
    develop:
      #- step: *build-android
      #- step: *deploy-android-internal
      - step: *build-ios
      - step: *deploy-ios-testflight

  custom:
    diagnostic-build:
      - step: *build-android-diagnostic
    
    deploy-internal:
      - step: *build-android
      - step: *deploy-android-internal
    
    build-only:
      - step: *build-android

    build-ios:
      - step: *build-ios

    deploy-ios-testflight:
      - step: *build-ios
      - step: *deploy-ios-testflight
