#!/bin/bash
set -e

source ./config.sh
echo "Using project: ${PROJECT_ID} in region: ${REGION}"

# Menu options
echo "==================================="
echo "Jigx MDK App Generator - Test Menu"
echo "==================================="
echo ""
echo "Select an app to generate:"
echo "1) Customer Management - List of customers with dynamic data"
echo "2) Expense Tracker - Track personal expenses by category"
echo "3) Task Manager - Simple todo list with status tracking"
echo "4) Inventory System - Product inventory with stock levels"
echo "5) Custom - Enter your own app description"
echo "q) Quit"
echo ""

echo -n "Enter your choice (1-5 or q) (auto-select random in 10s): "
choice=""
if read -t 10 choice; then
    # User provided input
    :
else
    # Timeout occurred, select random 1-4
    choice=$((RANDOM % 4 + 1))
    echo "$choice (timeout - random)"
fi

# Handle quit
if [[ $choice == "q" || $choice == "Q" ]]; then
    echo "Exiting..."
    exit 0
fi

# Set the prompt based on choice
case $choice in
    1)
        USER_PROMPT="Build customer management system. Store contacts in dynamic database. Track name, email, phone, company, address, notes. List view with search/filter by company or name. Detail screen shows full profile with call/email actions. Add/edit forms with validation. Include activity history tracking."
        APP_TYPE="customer-management"
        ;;
    2)
        USER_PROMPT="Build expense tracker app. Categories: Food, Transport, Entertainment, Bills, Other. Capture amount, date, merchant, receipt photo, notes. Monthly summary dashboard shows spending by category. List view filters by date range and category. Quick-add button for common expenses. Reports."
        APP_TYPE="expense-tracker"
        ;;
    3)
        USER_PROMPT="Build task management system. Track title, description, due date, priority (High/Medium/Low), status (Todo/In Progress/Done). Group by project or category. Sort by due date or priority. Show overdue items in red. Quick status toggle from list. Add recurring task support. Include completion stats."
        APP_TYPE="task-manager"
        ;;
    4)
        USER_PROMPT="Build inventory tracking system. Products with SKU, name, description, category, unit price. Track current stock, reorder point, preferred supplier. Low stock alerts when below reorder point. Search by SKU or name. Barcode scanner integration. Stock adjustment actions (receive/sell/adjust). Movement history log."
        APP_TYPE="inventory-system"
        ;;
    5)
        echo ""
        echo "Enter your custom app description:"
        read -r USER_PROMPT
        APP_TYPE="custom-app"
        ;;
    *)
        echo "Invalid choice. Exiting."
        exit 1
        ;;
esac

# Generate unique session ID
SESSION_ID="${APP_TYPE}-$(date +%Y%m%d-%H%M%S)-${RANDOM}"
echo ""
echo "Session ID: ${SESSION_ID}"
echo "Generating: ${USER_PROMPT}"
echo ""

# Ask for execution mode with 3 second timeout
echo -n "Run synchronously (wait for completion)? [Y/n] (auto-yes in 5s): "
sync_mode=""
if read -t 5 sync_mode; then
    # User provided input
    :
else
    # Timeout occurred, default to Y
    echo "Y (timeout)"
    sync_mode="Y"
fi

WAIT_FLAG="--wait"
if [[ $sync_mode =~ ^[Nn]$ ]]; then
    WAIT_FLAG="--async"
fi

# Base64 encode the prompt to avoid escaping issues
USER_PROMPT_B64=$(echo -n "${USER_PROMPT}" | base64)

# Execute with unique session
echo "Starting Cloud Run job..."
gcloud run jobs execute claude-code-jigx \
  --region=${REGION} \
  --update-env-vars="SESSION_ID=${SESSION_ID},USER_PROMPT_B64=${USER_PROMPT_B64}" \
  ${WAIT_FLAG}

echo ""
echo "Execution initiated!"
echo "Output location: gs://${PROJECT_ID}-claude-outputs/sessions/${SESSION_ID}/output.json"

# If async, offer to check status
if [[ $sync_mode =~ ^[Nn]$ ]]; then
    echo ""
    echo "To check execution status, run:"
    echo "gcloud run jobs executions list --job=claude-code-jigx --region=${REGION}"
else
    # Download the result if sync
    echo ""
    echo "Downloading output..."
    mkdir -p outputs
    if gsutil cp "gs://${PROJECT_ID}-claude-outputs/sessions/${SESSION_ID}/output.json" "./outputs/${SESSION_ID}-output.json" 2>/dev/null; then
        echo "Output saved to: ./outputs/${SESSION_ID}-output.json"
        echo ""
        echo "Preview (first 20 lines):"
        head -20 "./outputs/${SESSION_ID}-output.json" | python3 -m json.tool 2>/dev/null || cat "./outputs/${SESSION_ID}-output.json" | head -20
    else
        echo "No output file found - check logs for errors"
    fi
fi