#!/usr/bin/env bash
# Dev cycle: ASCF CLI compile → sync rawfile → build HAP → install → start + hdc rport
# Prerequisite: ./scripts/debug-server.sh start (in another terminal)
# FlexUIEngine loads jsfwk.js first (via EntryAbility), then FlexView loads component pack.js
source "$(cd "$(dirname "$0")/.." && pwd)/scripts/_config.sh"

mode="development"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --release) mode="release"; shift ;;
    -*)
      err "Unknown option: $1"
      echo "Usage: $0 [--release]"
      exit 1
      ;;
    *) mode="$1"; shift ;;
  esac
done

log "=== Dev cycle: compile ASCF → sync → HAP → install → start (mode=$mode) ==="

# Step 1: Compile ASCF AI-demo using the shared function
compile_ascf_ai_demo "$mode"

# Step 2: Sync compiled ASCF AI-demo → flexui-engine rawfile/ascf-ai-demo/
log "Syncing ASCF AI-demo to rawfile/ascf-ai-demo/..."
if [ ! -d "$ASCF_DEMO_RAW" ]; then
  err "ASCF demo rawfile not found at: $ASCF_DEMO_RAW"
  exit 1
fi
engine_ascf_dir="$ENTRY_DIR/src/main/resources/rawfile/ascf-ai-demo"
mkdir -p "$engine_ascf_dir"
cp -r "$ASCF_DEMO_RAW/"* "$engine_ascf_dir/"
log "Synced to $engine_ascf_dir/"
log "  app.js:     $(wc -c < "$engine_ascf_dir/app.js" 2>/dev/null || echo 'N/A') bytes"
log "  app.css.js: $(wc -c < "$engine_ascf_dir/app.css.js" 2>/dev/null || echo 'N/A') bytes"

# Step 3: Build HAP
log "Building HAP (hvigorw)..."
cd "$REPO_ROOT/flexui-engine"
"$HVIGORW" $HVIGORW_ARGS -p buildMode=debug assembleHap --no-daemon 2>&1 | tail -10
log "HAP built: $(ls -lh "$HAP" | awk '{print $5}')"

# Step 4: Install (hdc on Windows can't take MSYS/D:/ absolute paths — it
# concatenates them onto the current dir → double-path. Reuse install.sh's
# relative-path approach: cd into ENTRY_DIR and pass the rel path.)
log "Installing HAP on $DEVICE..."
_hap_rel="build/default/outputs/default/entry-default-signed.hap"
cd "$ENTRY_DIR"
hdc -t "$DEVICE" install -r "$_hap_rel" 2>&1

# Step 5: Start
log "Force-stopping previous instance..."
hdc -t "$DEVICE" shell aa force-stop "$BUNDLE" 2>&1 || true
sleep 1
log "Starting app..."
hdc -t "$DEVICE" shell aa start -a EntryAbility -b "$BUNDLE" 2>&1

# Step 6: hdc port forwarding for CDP inspector
DEBUG_PORT=38989
log "=== Debug: hdc rport forwarding ==="

existing_rport=$(hdc fport ls 2>&1 | grep "tcp:${DEBUG_PORT}" || true)
if [ -n "$existing_rport" ]; then
  log "Port ${DEBUG_PORT} already forwarded: $existing_rport"
else
  log "Forwarding hdc rport tcp:${DEBUG_PORT} tcp:${DEBUG_PORT}..."
  hdc rport "tcp:${DEBUG_PORT}" "tcp:${DEBUG_PORT}" 2>&1
  sleep 1
fi

log "hdc fport ls:"
hdc fport ls 2>&1

log "=== Dev cycle complete ==="
log "Device: $DEVICE  Bundle: $BUNDLE"
log "Debug server: http://localhost:${DEBUG_PORT}/front_end/inspector.html"