#!/bin/bash
# ============================================================================
# Ponshu Room Lite - 店舗向けAPKビルドスクリプト
# IS_BUSINESS_APP=true / IS_PRO_VERSION=false
# ============================================================================

set -e

TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)
OUTPUT_DIR="build/apk_releases/$TIMESTAMP"
mkdir -p "$OUTPUT_DIR"

# APIキー (.env から読み込む)
if [ -f "$(dirname "$0")/.env" ]; then
  export $(grep -v '^#' "$(dirname "$0")/.env" | xargs)
fi
MAITA_KEY="${MAITA_API_KEY:?MAITA_API_KEY is not set in .env}"
EIJI_KEY="${EIJI_API_KEY:?EIJI_API_KEY is not set in .env}"

# build.gradle.kts バックアップ
GRADLE_FILE="android/app/build.gradle.kts"
BACKUP_FILE="android/app/build.gradle.kts.backup"
cp "$GRADLE_FILE" "$BACKUP_FILE"

cleanup() {
    if [ -f "$BACKUP_FILE" ]; then
        cp "$BACKUP_FILE" "$GRADLE_FILE"
        rm "$BACKUP_FILE"
    fi
}
trap cleanup EXIT

echo "============================================================================"
echo "Ponshu Room Lite - Business APK Build"
echo "============================================================================"
echo "Output: $OUTPUT_DIR"
echo ""

sed -i 's/applicationId = "com.posimai.ponshu_room"/applicationId = "com.posimai.ponshu_room_lite"/' "$GRADLE_FILE"

echo "[1/2] Building Maita Business..."
flutter build apk --release \
  --dart-define=GEMINI_API_KEY=$MAITA_KEY \
  --dart-define=IS_PRO_VERSION=false \
  --dart-define=IS_BUSINESS_APP=true \
  --dart-define=USE_PROXY=false

cp build/app/outputs/flutter-apk/app-release.apk "$OUTPUT_DIR/ponshu_room_business_maita.apk"
echo "Saved: $OUTPUT_DIR/ponshu_room_business_maita.apk"
echo ""

echo "[2/2] Building Eiji Business..."
flutter build apk --release \
  --dart-define=GEMINI_API_KEY=$EIJI_KEY \
  --dart-define=IS_PRO_VERSION=false \
  --dart-define=IS_BUSINESS_APP=true \
  --dart-define=USE_PROXY=false

cp build/app/outputs/flutter-apk/app-release.apk "$OUTPUT_DIR/ponshu_room_business_eiji.apk"
echo "Saved: $OUTPUT_DIR/ponshu_room_business_eiji.apk"
echo ""

echo "============================================================================"
echo "Business build completed!"
echo "============================================================================"
ls -lh "$OUTPUT_DIR"
