#!/usr/bin/env bash
# App Store Connect API Helper Script
set -euo pipefail

# קבלת פרמטרים
if [[ $# -lt 4 ]]; then
  echo "Usage: $0 <bundle_id> <api_key_id> <issuer_id> <key_path>"
  echo "Example: $0 com.yourcompany.yourapp ABCD1234 12345678-1234-1234-1234-123456789012 /path/to/AuthKey_ABCD1234.p8"
  exit 1
fi

BUNDLE_ID="$1"
APP_STORE_CONNECT_API_KEY_ID="$2"
APP_STORE_CONNECT_API_ISSUER_ID="$3"
APP_STORE_CONNECT_API_KEY_PATH="$4"

echo "📋 Received parameters:"
echo "   Bundle ID: $BUNDLE_ID"
echo "   API Key ID: $APP_STORE_CONNECT_API_KEY_ID"
echo "   Issuer ID: $APP_STORE_CONNECT_API_ISSUER_ID"
echo "   Key Path: $APP_STORE_CONNECT_API_KEY_PATH"

# בדיקה שקובץ המפתח קיים
[[ ! -f "$APP_STORE_CONNECT_API_KEY_PATH" ]] && { 
  echo "❌ API key file not found: $APP_STORE_CONNECT_API_KEY_PATH"
  exit 1
}

# בדיקה שהקובץ קריא
[[ ! -r "$APP_STORE_CONNECT_API_KEY_PATH" ]] && {
  echo "❌ API key file not readable: $APP_STORE_CONNECT_API_KEY_PATH"
  exit 1
}

# בדיקה שהקובץ לא ריק
[[ ! -s "$APP_STORE_CONNECT_API_KEY_PATH" ]] && {
  echo "❌ API key file is empty: $APP_STORE_CONNECT_API_KEY_PATH"
  exit 1
}

echo "✅ API key file found and readable: $APP_STORE_CONNECT_API_KEY_PATH"
echo "✅ API key file size: $(wc -c < "$APP_STORE_CONNECT_API_KEY_PATH") bytes"

# בדיקה שה-API key ID תואם לקובץ
key_filename=$(basename "$APP_STORE_CONNECT_API_KEY_PATH")
if [[ "$key_filename" == "AuthKey_${APP_STORE_CONNECT_API_KEY_ID}.p8" ]]; then
  echo "✅ API key ID matches key file name"
else
  echo "⚠️  Warning: API key ID ($APP_STORE_CONNECT_API_KEY_ID) doesn't match key file name ($key_filename)"
fi

# פונקציה ליצירת JWT Token
generate_jwt_token() {
  # דורש Ruby (קיים ב-macOS), לא תלוי בג׳מס חיצוניים
  APP_STORE_CONNECT_API_KEY_ID="$APP_STORE_CONNECT_API_KEY_ID" \
  APP_STORE_CONNECT_API_ISSUER_ID="$APP_STORE_CONNECT_API_ISSUER_ID" \
  APP_STORE_CONNECT_API_KEY_PATH="$APP_STORE_CONNECT_API_KEY_PATH" \
  ruby -ropenssl -rjson -rbase64 -e '
    kid = ENV["APP_STORE_CONNECT_API_KEY_ID"]
    iss = ENV["APP_STORE_CONNECT_API_ISSUER_ID"]
    key_path = ENV["APP_STORE_CONNECT_API_KEY_PATH"]

    header  = { alg: "ES256", kid: kid, typ: "JWT" }
    now     = Time.now.to_i
    payload = { iss: iss, iat: now, exp: now + 900, aud: "appstoreconnect-v1" }

    def enc(obj) Base64.urlsafe_encode64(obj.to_json, padding: false) end
    unsigned = [enc(header), enc(payload)].join(".")

    key = OpenSSL::PKey.read(File.read(key_path))
    # חתימה ב-ECDSA → מתקבל DER; צריך להמיר ל-r||s באורך 32+32
    der = key.dsa_sign_asn1(OpenSSL::Digest::SHA256.digest(unsigned))
    asn1 = OpenSSL::ASN1.decode(der)
    r = asn1.value[0].value.to_s(2).rjust(32, "\x00")
    s = asn1.value[1].value.to_s(2).rjust(32, "\x00")
    sig = Base64.urlsafe_encode64(r + s, padding: false)

    puts [unsigned, sig].join(".")
  '
}


# פונקציה לבדיקת אפליקציה לפי Bundle ID
get_app_id() {
  local bundle_id="$1"
  local token="$2"
  
  echo "🔍 Searching for app with bundle ID: $bundle_id" >&2
  
  # URL encode ה-bundle_id והסוגריים
  local encoded_bundle_id=$(printf '%s' "$bundle_id" | sed 's/\./\%2E/g')
  
  # יצירת URL מלא עם encoding נכון של הסוגריים
  local full_url="https://api.appstoreconnect.apple.com/v1/apps?filter%5BbundleId%5D=$encoded_bundle_id"
  
  # בדיקה אם ה-JWT token תקין
  echo "🔍 Validating JWT token..." >&2
  local token_parts=$(echo "$token" | tr '.' '\n')
  local header=$(echo "$token_parts" | head -n1)
  local payload=$(echo "$token_parts" | head -n2 | tail -n1)
  
  echo "🔍 Token parts count: $(echo "$token_parts" | wc -l)" >&2
  echo "🔍 Header: $header" >&2
  echo "🔍 Payload: $payload" >&2
  
  # פענוח ה-payload
  echo "🔍 Decoding JWT payload..." >&2
  local decoded_payload=$(echo "$payload" | base64 -d 2>/dev/null || echo "Failed to decode")
  echo "🔍 Decoded payload: $decoded_payload" >&2
  
    
  # בדיקה פשוטה של JWT token
  echo "🔍 Testing JWT with simple API call..." >&2
  echo "⏰ Current time before simple test: $(date)" >&2
  local simple_test=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $token" \
    "https://api.appstoreconnect.apple.com/v1/apps")
  echo "🔍 Simple JWT test response: '$simple_test'" >&2
  echo "🔍 Simple JWT test HTTP code: '$(echo "$simple_test" | tail -n1)'" >&2
  echo "🔍 Simple JWT test body (first 200 chars): '$(echo "$simple_test" | sed '$d' | head -c 200)...'" >&2
  echo "⏰ Current time after simple test: $(date)" >&2
  
  # נסה ראשית בלי פילטר כדי לוודא שהחיבור עובד
  echo "🔍 Testing connection with all apps first..." >&2
  echo "⏰ Current time before all apps test: $(date)" >&2
  local all_apps_test=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $token" \
    "https://api.appstoreconnect.apple.com/v1/apps")
  echo "🔍 All apps test response: '$(echo "$all_apps_test" | tail -n1)'" >&2
  echo "🔍 All apps test full response (first 200 chars): '$(echo "$all_apps_test" | head -c 200)...'" >&2
  echo "⏰ Current time after all apps test: $(date)" >&2
  
  # נסה את אותה הקריאה שוב - האם זה עדיין עובד?
  echo "🔍 Testing same apps call again to check token consistency..." >&2
  local all_apps_test2=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $token" \
    "https://api.appstoreconnect.apple.com/v1/apps")
  echo "🔍 Second all apps test response: '$(echo "$all_apps_test2" | tail -n1)'" >&2
  echo "🔍 Second all apps test full response (first 200 chars): '$(echo "$all_apps_test2" | head -c 200)...'" >&2
  
  echo "⏰ Current time before filtered request: $(date)" >&2
  echo "🔗 Exact URL being called: https://api.appstoreconnect.apple.com/v1/apps?filter[bundleId]=$encoded_bundle_id" >&2
  
  # ננסה גם בלי URL encoding
  echo "🔗 Trying also without URL encoding: https://api.appstoreconnect.apple.com/v1/apps?filter[bundleId]=$bundle_id" >&2
  local response_no_encoding=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $token" \
    "https://api.appstoreconnect.apple.com/v1/apps?filter[bundleId]=$bundle_id")
  echo "🔍 No encoding response: '$(echo "$response_no_encoding" | tail -n1)'" >&2
  echo "🔍 No encoding body (first 100 chars): '$(echo "$response_no_encoding" | sed '$d' | head -c 100)...'" >&2
  
  # בדיקה נוספת - ננסה עם quotes בURL
  echo "🔗 Trying with URL in single quotes..." >&2
  local response_quoted=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $token" \
    'https://api.appstoreconnect.apple.com/v1/apps?filter[bundleId]='"$bundle_id")
  echo "🔍 Quoted response: '$(echo "$response_quoted" | tail -n1)'" >&2
  
  local response=$(curl -s -w "\n%{http_code}" -H "Authorization: Bearer $token" \
    "$full_url")
  echo "⏰ Current time after filtered request: $(date)" >&2
  
  echo "🔍 Raw curl response: '$response'" >&2
  
  # בדיקה נוספת עם curl verbose
  echo "🔍 Testing with verbose curl..." >&2
  local verbose_response=$(curl -v -H "Authorization: Bearer $token" \
    "$full_url" 2>&1)
  echo "🔍 Verbose response (first 500 chars): '$(echo "$verbose_response" | head -c 500)...'" >&2
  
  local http_code=$(echo "$response" | tail -n1)
  local api_response=$(echo "$response" | sed '$d')
  
  echo "📡 HTTP Status Code: '$http_code'" >&2
  echo "📡 API Response length: ${#api_response}" >&2
  echo "📡 API Response: '$api_response'" >&2
  
  # בדיקה אם התגובה ריקה
  if [[ -z "$api_response" ]]; then
    echo "❌ Empty response from API" >&2
    echo ""
    return
  fi
  
  # בדיקה אם יש שגיאת HTTP
  if [[ "$http_code" != "200" ]]; then
    echo "❌ HTTP Error: $http_code" >&2
    echo ""
    return
  fi
  
  local app_id=$(echo "$api_response" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    if data.get('data') and len(data['data']) > 0:
        print(data['data'][0]['id'])
    else:
        print('')
        if data.get('errors'):
            print('API Errors:', file=sys.stderr)
            for error in data['errors']:
                print(f\"  - {error.get('detail', 'Unknown error')}\", file=sys.stderr)
        elif not data.get('data'):
            print('No data returned from API', file=sys.stderr)
        else:
            print('Data array is empty', file=sys.stderr)
except Exception as e:
    print('')
    print(f'Python parsing error: {e}', file=sys.stderr)
    print(f'Raw response: {sys.stdin.read()}', file=sys.stderr)
" 2>&1)
  
  echo "$app_id"
}

# פונקציה לקבלת הבנייה האחרונה
get_latest_build() {
  local app_id="$1"
  local token="$2"
  
  echo "🔍 Looking for builds for app ID: $app_id" >&2
  # ננסה למיין לפי תאריך העלאה במקום גרסה
  local builds_url="https://api.appstoreconnect.apple.com/v1/builds?filter%5Bapp%5D=$app_id&sort=-uploadedDate&limit=5"
  echo "🔗 Builds URL: $builds_url" >&2
  
  local response=$(curl -s -H "Authorization: Bearer $token" "$builds_url")
  echo "🔍 Builds response length: ${#response}" >&2
  echo "🔍 Builds response (first 300 chars): $(echo "$response" | head -c 300)..." >&2
  
  echo "$response" | python3 -c "
import sys, json
from datetime import datetime
try:
    data = json.load(sys.stdin)
    if data.get('data') and len(data['data']) > 0:
        builds = data['data']
        print(f\"🔍 Found {len(builds)} builds total\", file=sys.stderr)
        
        # נדפיס את כל הbuilds כדי לראות מה יש
        for i, build in enumerate(builds):
            version = build['attributes']['version']
            uploaded_date = build['attributes'].get('uploadedDate', '')
            expired = build['attributes'].get('expired', False)
            processing_state = build['attributes'].get('processingState', 'unknown')
            print(f\"🔍 Build {i+1}: Version={version}, Uploaded={uploaded_date}, Expired={expired}, State={processing_state}\", file=sys.stderr)
        
        # נחפש את הbuild הראשון שלא פג תוקף
        for build in builds:
            expired = build['attributes'].get('expired', False)
            if not expired:
                processing_state = build['attributes'].get('processingState', 'unknown')
                uses_non_exempt_encryption = build['attributes'].get('usesNonExemptEncryption', 'unknown')
                expiration_date = build['attributes'].get('expirationDate', '')
                
                print(f\"🔍 Selected non-expired build: ID={build['id']}, Version={build['attributes']['version']}, State={processing_state}\", file=sys.stderr)
                print(f\"{build['id']}|{build['attributes']['version']}|{processing_state}|{uses_non_exempt_encryption}|{expired}\")
                exit()
        
        # אם כל הbuilds פגו תוקף, נחזיר את החדש ביותר
        build = builds[0]
        processing_state = build['attributes'].get('processingState', 'unknown')
        uses_non_exempt_encryption = build['attributes'].get('usesNonExemptEncryption', 'unknown')
        expired = build['attributes'].get('expired', False)
        
        print(f\"🔍 All builds expired, returning latest: ID={build['id']}, Version={build['attributes']['version']}\", file=sys.stderr)
        print(f\"{build['id']}|{build['attributes']['version']}|{processing_state}|{uses_non_exempt_encryption}|{expired}\")
    else:
        print('')
except Exception as e:
    print('', file=sys.stderr)
    print(f'Error parsing build response: {e}', file=sys.stderr)
    print('')
"
}

# פונקציה ליצירת release notes דינמי
generate_release_notes() {
  local version="$1"
  
  # בדיקה אם יש הגדרות סביבה ל-release notes
  if [[ "${RELEASE_NOTES_AUTO_GENERATE:-}" == "true" ]]; then
    local notes_en="${RELEASE_NOTES_EN:-}"
    local notes_he="${RELEASE_NOTES_HE:-}"
    
    # אם לא הוגדרו הודעות ידנית, השתמש בברירת מחדל
    if [[ -z "$notes_en" ]]; then
      notes_en="Bug fixes and performance improvements. Enhanced user experience and updated security features."
    fi
    
    if [[ -z "$notes_he" ]]; then
      notes_he="תיקון באגים ושיפור ביצועים. שיפור חוויית המשתמש ועדכון תכונות אבטחה."
    fi
    
    # הוספת מידע דינמי אם מבוקש
    if [[ "${RELEASE_NOTES_INCLUDE_VERSION:-}" == "true" ]]; then
      notes_en="Version $version: $notes_en"
      notes_he="גרסה $version: $notes_he"
    fi
    
    if [[ "${RELEASE_NOTES_INCLUDE_DATE:-}" == "true" ]]; then
      local current_date=$(date '+%d/%m/%Y')
      notes_en="$notes_en Released: $current_date"
      notes_he="$notes_he תאריך שחרור: $current_date"
    fi
    
    echo "🔤 Generated release notes:"
    echo "   English: $notes_en"
    echo "   Hebrew: $notes_he"
    
    # החזרת הנתונים בפורמט JSON
    cat << EOF
{
  "en-US": "$notes_en",
  "he": "$notes_he"
}
EOF
  else
    echo "⚠️  Release notes auto-generation disabled"
    echo ""
  fi
}

# פונקציה להוספת release notes לגרסה
add_release_notes() {
  local version_id="$1"
  local token="$2"
  local version="$3"
  
  echo "📝 Adding release notes to version..."
  
  # יצירת release notes
  local release_notes_json=$(generate_release_notes "$version")
  
  if [[ -z "$release_notes_json" ]]; then
    echo "⚠️  No release notes generated - skipping"
    return 0
  fi
  
  # הוספת release notes לאנגלית
  local notes_en=$(echo "$release_notes_json" | python3 -c "import sys, json; data=json.load(sys.stdin); print(data.get('en-US', ''))")
  local notes_he=$(echo "$release_notes_json" | python3 -c "import sys, json; data=json.load(sys.stdin); print(data.get('he', ''))")
  
  # הוספת localization לאנגלית
  if [[ -n "$notes_en" ]]; then
    local en_localization_data='{
      "data": {
        "type": "appStoreVersionLocalizations",
        "attributes": {
          "locale": "en-US",
          "whatsNew": "'"$notes_en"'"
        },
        "relationships": {
          "appStoreVersion": {
            "data": {
              "type": "appStoreVersions",
              "id": "'"$version_id"'"
            }
          }
        }
      }
    }'
    
    local en_response=$(curl -s -X POST \
      -H "Authorization: Bearer $token" \
      -H "Content-Type: application/json" \
      -d "$en_localization_data" \
      "https://api.appstoreconnect.apple.com/v1/appStoreVersionLocalizations")
    
    echo "📝 English release notes response: $(echo "$en_response" | python3 -c "import sys, json; data=json.load(sys.stdin); print('SUCCESS' if data.get('data') else 'FAILED')" 2>/dev/null || echo "FAILED")"
  fi
  
  # הוספת localization לעברית
  if [[ -n "$notes_he" ]]; then
    local he_localization_data='{
      "data": {
        "type": "appStoreVersionLocalizations", 
        "attributes": {
          "locale": "he",
          "whatsNew": "'"$notes_he"'"
        },
        "relationships": {
          "appStoreVersion": {
            "data": {
              "type": "appStoreVersions",
              "id": "'"$version_id"'"
            }
          }
        }
      }
    }'
    
    local he_response=$(curl -s -X POST \
      -H "Authorization: Bearer $token" \
      -H "Content-Type: application/json" \
      -d "$he_localization_data" \
      "https://api.appstoreconnect.apple.com/v1/appStoreVersionLocalizations")
    
    echo "📝 Hebrew release notes response: $(echo "$he_response" | python3 -c "import sys, json; data=json.load(sys.stdin); print('SUCCESS' if data.get('data') else 'FAILED')" 2>/dev/null || echo "FAILED")"
  fi
}

# פונקציה לשליחה לאישור
submit_for_review() {
  local app_id="$1"
  local build_id="$2"
  local token="$3"
  
  # בדיקה של כל הגרסאות קודם
  echo "🔍 Checking all app store versions..." >&2
  local all_versions=$(curl -s -H "Authorization: Bearer $token" \
    "https://api.appstoreconnect.apple.com/v1/appStoreVersions?filter%5Bapp%5D=$app_id")
  
  echo "🔍 All versions response length: ${#all_versions}" >&2
  echo "🔍 All versions (first 300 chars): $(echo "$all_versions" | head -c 300)..." >&2
  
  # עיבוד הגרסאות
  echo "$all_versions" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    if data.get('errors'):
        for error in data['errors']:
            error_detail = error.get('detail', 'Unknown error')
            error_code = error.get('code', 'Unknown code')
            print(f'📋 API Error checking versions ({error_code}): {error_detail}', file=sys.stderr)
    elif data.get('data'):
        print(f'📋 Found {len(data[\"data\"])} app store versions:', file=sys.stderr)
        for version in data['data']:
            state = version['attributes']['appStoreState']
            version_string = version['attributes']['versionString']
            created_date = version['attributes'].get('createdDate', 'unknown')
            print(f'📋   Version {version_string}: {state} (created: {created_date})', file=sys.stderr)
    else:
        print('📋 No versions found', file=sys.stderr)
except Exception as e:
    print(f'📋 Error checking versions: {e}', file=sys.stderr)
" 2>&1
  
  # בדיקה אם יש version in review כבר
  echo "🔍 Checking for existing versions in review..." >&2
  local existing_submission=$(curl -s -H "Authorization: Bearer $token" \
    "https://api.appstoreconnect.apple.com/v1/appStoreVersions?filter%5Bapp%5D=$app_id&filter%5BappStoreState%5D=PREPARE_FOR_SUBMISSION,WAITING_FOR_REVIEW,IN_REVIEW,PENDING_DEVELOPER_RELEASE,READY_FOR_SALE")
  
  echo "🔍 Existing submissions response length: ${#existing_submission}" >&2
  echo "🔍 Existing submissions (first 200 chars): $(echo "$existing_submission" | head -c 200)..." >&2
  
  local has_pending=$(echo "$existing_submission" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    # בדיקה אם יש שגיאות (כמו 403)
    if data.get('errors'):
        for error in data['errors']:
            error_detail = error.get('detail', 'Unknown error')
            error_code = error.get('code', 'Unknown code')
            print(f'API Error ({error_code}): {error_detail}', file=sys.stderr)
        # אם יש שגיאת 403, נניח שאין גרסאות ממתינות
        print('false')
    elif data.get('data') and len(data['data']) > 0:
        for version in data['data']:
            state = version['attributes']['appStoreState']
            version_string = version['attributes']['versionString']
            print(f'Found version {version_string} in state: {state}', file=sys.stderr)
        print('true')
    else:
        print('false')
except Exception as e:
    print(f'Error checking existing versions: {e}', file=sys.stderr)
    print('false')
" 2>&1)
  
  if [[ "$has_pending" == "true" ]]; then
    echo "⚠️  App already has a version in active state that prevents new submissions"
    echo "💡 Possible states: PENDING_DEVELOPER_RELEASE, READY_FOR_SALE, or in review"
    echo "📱 Check App Store Connect to see current status"
    return 1
  fi
  
  # אם אין הרשאה לבדוק גרסאות (403 FORBIDDEN), ננסה ישירות
  echo "⚠️  Cannot check existing versions due to API permissions"
  echo "🔄 Attempting to create version directly..."
  
  # יצירת גרסה חדשה לאישור - השתמש בגרסה הנוכחית אם קיימת
  local version_string="${CURRENT_VERSION:-$(date +%Y.%m.%d)}"
  local version_data='{
    "data": {
      "type": "appStoreVersions",
      "attributes": {
        "platform": "IOS",
        "versionString": "'"$version_string"'",
        "releaseType": "AFTER_APPROVAL"
      },
      "relationships": {
        "app": {
          "data": {
            "type": "apps",
            "id": "'"$app_id"'"
          }
        },
        "build": {
          "data": {
            "type": "builds", 
            "id": "'"$build_id"'"
          }
        }
      }
    }
  }'
  
  local version_response=$(curl -s -X POST \
    -H "Authorization: Bearer $token" \
    -H "Content-Type: application/json" \
    -d "$version_data" \
    "https://api.appstoreconnect.apple.com/v1/appStoreVersions")
  
  local version_id=$(echo "$version_response" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    if data.get('data'):
        print(data['data']['id'])
    else:
        print('')
except:
    print('')
" 2>/dev/null)
  
  if [[ -z "$version_id" ]]; then
    echo "❌ Failed to create app store version"
    
    # ניתוח השגיאה
    local error_analysis=$(echo "$version_response" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    if data.get('errors'):
        for error in data['errors']:
            detail = error.get('detail', '')
            if 'current state' in detail.lower():
                print('🔍 LIKELY CAUSE: App already has a version in active state')
                print('💡 SOLUTION: Check App Store Connect for:')
                print('   • Version waiting for release (PENDING_DEVELOPER_RELEASE)')
                print('   • Version already published (READY_FOR_SALE)')
                print('   • Version in review process')
                print('')
            elif 'build could not be added' in detail.lower():
                print('🔍 LIKELY CAUSE: Build issue')
                print('💡 SOLUTION: Build may be expired or invalid')
                print('')
except:
    pass
" 2>/dev/null)
    
    echo "$error_analysis"
    echo "$version_response"
    return 1
  fi
  
  echo "✅ Created app store version: $version_id"
  
  # הוספת release notes לגרסה החדשה
  add_release_notes "$version_id" "$token" "$version_string"
  
  # שליחה לאישור
  local submission_data='{
    "data": {
      "type": "appStoreVersionSubmissions",
      "relationships": {
        "appStoreVersion": {
          "data": {
            "type": "appStoreVersions",
            "id": "'"$version_id"'"
          }
        }
      }
    }
  }'
  
  local submission_response=$(curl -s -X POST \
    -H "Authorization: Bearer $token" \
    -H "Content-Type: application/json" \
    -d "$submission_data" \
    "https://api.appstoreconnect.apple.com/v1/appStoreVersionSubmissions")
  
  echo "$submission_response" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    if data.get('data'):
        print('SUCCESS')
    else:
        print('FAILED')
        if data.get('errors'):
            for error in data['errors']:
                print(f\"Error: {error.get('detail', 'Unknown error')}\")
except:
    print('FAILED')
"
}

# פונקציה ראשית
main() {
  echo "🔑 Generating JWT token..."
  local token=$(generate_jwt_token)
  
  if [[ -z "$token" ]]; then
    echo "❌ Failed to generate JWT token"
    exit 1
  fi
  
  echo "✅ JWT token generated successfully (length: ${#token})"
  
  echo "🔍 Finding app with bundle ID: $BUNDLE_ID"
  local app_id=$(get_app_id "$BUNDLE_ID" "$token")
  
  if [[ -z "$app_id" ]]; then
    echo "❌ App not found with bundle ID: $BUNDLE_ID"
    exit 1
  fi
  
  echo "✅ Found app ID: $app_id"
  
  echo "📱 Getting latest build..."
  # קבלת פרטי הbuild עם debug
  local build_output=$(get_latest_build "$app_id" "$token" 2>&1)
  local build_info=$(echo "$build_output" | tail -n1)
  
  if [[ -z "$build_info" ]]; then
    echo "❌ No builds found for this app"
    exit 1
  fi
  
  # בדיקה אם יש לנו את כל הפרטים
  local parts_count=$(echo "$build_info" | tr '|' '\n' | wc -l)
  echo "🔍 Build info parts: $parts_count" >&2
  echo "🔍 Build info string: '$build_info'" >&2
  
  local build_id=$(echo "$build_info" | cut -d'|' -f1)
  local build_version=$(echo "$build_info" | cut -d'|' -f2)
  local build_processing_state=""
  local build_encryption=""
  local build_expired=""
  
  # אם יש לנו את כל החלקים
  if [[ $parts_count -ge 4 ]]; then
    build_processing_state=$(echo "$build_info" | cut -d'|' -f3)
    build_encryption=$(echo "$build_info" | cut -d'|' -f4)
  fi
  
  if [[ $parts_count -ge 5 ]]; then
    build_expired=$(echo "$build_info" | cut -d'|' -f5)
  fi
  
  echo "✅ Found latest build: $build_version (ID: $build_id)"
  echo "📋 Build processing state: $build_processing_state"
  echo "🔐 Uses non-exempt encryption: $build_encryption"
  echo "⏰ Build expired: $build_expired"
  
  # בדיקה אם הbuild פג תוקף
  if [[ "$build_expired" == "True" || "$build_expired" == "true" ]]; then
    echo "❌ Build has expired and cannot be submitted for review"
    echo "📱 You need to upload a new build to TestFlight"
    echo "💡 Use Xcode or the build script to create and upload a new build"
    exit 1
  fi
  
  # בדיקה אם הbuild מוכן לשליחה עם retry logic
  local retry_count=0
  local max_retries=5
  
  while [[ $retry_count -lt $max_retries ]]; do
    if [[ -n "$build_processing_state" && "$build_processing_state" != "VALID" ]]; then
      if [[ $retry_count -eq 0 ]]; then
        echo "⚠️  Build is not in VALID state (current: $build_processing_state)"
        echo "🔄 Will retry up to $max_retries times with 1-minute intervals..."
      fi
      
      ((retry_count++))
      echo "🔄 Attempt $retry_count/$max_retries - Build still processing (state: $build_processing_state)"
      
      if [[ $retry_count -lt $max_retries ]]; then
        echo "⏳ Waiting 60 seconds before next check..."
        sleep 60
        
        # בדיקה מחדש של מצב הbuild
        echo "🔍 Checking build state again..."
        local build_output=$(get_latest_build "$app_id" "$token" 2>&1)
        local build_info=$(echo "$build_output" | tail -n1)
        
        if [[ -n "$build_info" ]]; then
          local parts_count=$(echo "$build_info" | tr '|' '\n' | wc -l)
          if [[ $parts_count -ge 3 ]]; then
            build_processing_state=$(echo "$build_info" | cut -d'|' -f3)
            echo "📋 Updated build processing state: $build_processing_state"
          fi
        fi
      else
        echo "❌ Build did not become VALID after $max_retries attempts"
        echo "📱 Build must finish processing in TestFlight before submission"
        echo "💡 Try again later or submit manually via App Store Connect"
        exit 1
      fi
    else
      # Build is VALID or state unknown - proceed with submission
      break
    fi
  done
  
  if [[ -z "$build_processing_state" ]]; then
    echo "⚠️  Could not determine build processing state"
    echo "🔄 Attempting submission anyway..."
  else
    echo "✅ Build is ready for submission (state: $build_processing_state)"
  fi
  
  echo "🚀 Submitting for App Store review..."
  local result=$(submit_for_review "$app_id" "$build_id" "$token")
  
  if [[ "$result" == "SUCCESS" ]]; then
    echo "✅ Successfully submitted for review!"
    echo "📱 Check status at: https://appstoreconnect.apple.com/"
  else
    echo "❌ Submission failed:"
    echo "$result"
    exit 1
  fi
}

# בדיקה אם הסקריפט נקרא ישירות
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  # הפרמטרים כבר נבדקו בתחילת הסקריפט
  main
fi
