#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=../env/common.sh
source "${SCRIPT_DIR}/../env/common.sh"
load_local_env

VENDOR="${EUV_QUICKAPP_VENDOR:-all}"
SHELL_ONLY=0
OUT_BASE="${REPO_ROOT}/dist/quickapp"

while [ "$#" -gt 0 ]; do
  case "$1" in
    --vendor)
      VENDOR="${2:-all}"
      shift 2
      ;;
    --shell-only)
      SHELL_ONLY=1
      shift
      ;;
    --out-dir)
      OUT_BASE="${2:-${REPO_ROOT}/dist/quickapp}"
      shift 2
      ;;
    *)
      shift
      ;;
  esac
done

TARGETS=()
if [ "${VENDOR}" = "all" ]; then
  TARGETS=(alliance huawei)
else
  TARGETS=("${VENDOR}")
fi

WASM_STAGE="${REPO_ROOT}/target/mobile-hosts/quickapp-wasm"
HAS_WASM=0
if [ "${SHELL_ONLY}" -eq 0 ] && command -v wasm-pack >/dev/null 2>&1; then
  mkdir -p "${WASM_STAGE}"
  log_info "Building Release WebAssembly core for QuickApp hosts..."
  (
    cd "${REPO_ROOT}/example"
    wasm-pack build --target web --release --out-dir "${WASM_STAGE}"
  )
  if [ -f "${WASM_STAGE}/euv_example_bg.wasm" ]; then
    WASM_SCHEMA="$(strings "${WASM_STAGE}/euv_example_bg.wasm" | grep -c "euv.ai.schema.v1" || true)"
    log_info "QuickApp WASM built ($(du -h "${WASM_STAGE}/euv_example_bg.wasm" | cut -f1)), release ai-schema=${WASM_SCHEMA}"
    [ "${WASM_SCHEMA}" -eq 0 ]
    HAS_WASM=1
  fi
fi

emit_quickapp_project() {
  local v="$1"
  local pkg_id="$2"
  local min_ver="$3"
  local out_dir="${OUT_BASE}/${v}"

  mkdir -p "${out_dir}/src/Index" "${out_dir}/src/Common"

  cat > "${out_dir}/package.json" <<EOF
{
  "name": "euv-quickapp-${v}",
  "version": "0.48.2",
  "description": "Euv Native Rust UI QuickApp Host (${v})",
  "scripts": {
    "build": "hap build",
    "release": "hap release"
  }
}
EOF

  cat > "${out_dir}/src/manifest.json" <<EOF
{
  "package": "${pkg_id}",
  "name": "Euv Studio",
  "versionName": "0.48.2",
  "versionCode": 471,
  "minPlatformVersion": ${min_ver},
  "icon": "/Common/logo.png",
  "features": [
    { "name": "system.router" },
    { "name": "system.storage" },
    { "name": "system.clipboard" },
    { "name": "system.device" },
    { "name": "system.network" },
    { "name": "system.vibrator" },
    { "name": "system.prompt" },
    { "name": "system.share" }
  ],
  "config": {
    "logLevel": "off",
    "designWidth": 750
  },
  "router": {
    "entry": "Index",
    "pages": {
      "Index": {
        "component": "index"
      }
    }
  },
  "display": {
    "titleBar": false,
    "fullScreen": true,
    "statusBarImmersive": true,
    "statusBarTextStyle": "light",
    "backgroundColor": "#09090B"
  }
}
EOF

  if [ -f "${REPO_ROOT}/scripts/env/generate-icon.py" ]; then
    python3 "${REPO_ROOT}/scripts/env/generate-icon.py" \
      "${out_dir}/src/Common/logo.png" 192 "${EUV_APP_ICON:-}" || true
  fi

  cat > "${out_dir}/src/app.ux" <<'EOF'
<script>
import device from '@system.device';
import network from '@system.network';

export default {
  euvDeviceInfo: null,
  onCreate() {
    device.getInfo({
      success: (info) => {
        this.euvDeviceInfo = info;
      }
    });
    network.subscribe({
      callback: (status) => {
        this.euvNetworkType = status && status.type ? status.type : 'unknown';
      }
    });
  },
  onDestroy() {
    network.unsubscribe();
  }
};
</script>
EOF

  cat > "${out_dir}/src/Index/index.ux" <<EOF
<template>
  <div class="euv-root">
    <canvas
      id="euv-canvas"
      class="euv-canvas"
      ontouchstart="onTouchStart"
      ontouchmove="onTouchMove"
      ontouchend="onTouchEnd"
      ontouchcancel="onTouchCancel"
    ></canvas>
    <input
      id="euv-ime-proxy"
      class="euv-ime-proxy"
      type="text"
      value="{{imeValue}}"
      onchange="onImeChange"
      onenterkeyclick="onImeConfirm"
    />
  </div>
</template>

<style>
  .euv-root {
    width: 750px;
    height: 100%;
    flex-direction: column;
    background-color: #09090b;
  }
  .euv-canvas {
    width: 750px;
    height: 100%;
  }
  .euv-ime-proxy {
    position: fixed;
    left: -9999px;
    top: -9999px;
    width: 1px;
    height: 1px;
    opacity: 0;
  }
</style>

<script>
import router from '@system.router';
import storage from '@system.storage';
import clipboard from '@system.clipboard';
import device from '@system.device';
import vibrator from '@system.vibrator';

const QUICKAPP_VENDOR = '${v}';

export default {
  private: {
    imeValue: '',
    running: false,
    canvasCtx: null,
    designWidth: 750
  },
  onReady() {
    const canvas = this.\$element('euv-canvas');
    if (canvas && typeof canvas.getContext === 'function') {
      this.canvasCtx = canvas.getContext('2d');
    }
    device.getInfo({
      success: (info) => {
        this.deviceInfo = info;
      }
    });
    this.running = true;
  },
  onShow() {
    this.running = true;
  },
  onHide() {
    this.running = false;
  },
  onDestroy() {
    this.running = false;
    this.canvasCtx = null;
  },
  onBackPress() {
    return false;
  },
  executeHostCommand(cmd) {
    if (!cmd) return;
    switch (cmd.kind) {
      case 'routerPush':
        router.push({ uri: cmd.uri });
        break;
      case 'routerBack':
        router.back();
        break;
      case 'storageSet':
        storage.set({ key: cmd.key, value: cmd.value });
        break;
      case 'storageDelete':
        storage.delete({ key: cmd.key });
        break;
      case 'storageClear':
        storage.clear();
        break;
      case 'clipboardSet':
        clipboard.set({ text: cmd.text || '' });
        break;
      case 'vibrateShort':
        vibrator.vibrate({ mode: 'short' });
        break;
      default:
        break;
    }
  },
  onTouchStart(e) {
    void QUICKAPP_VENDOR;
    void e;
  },
  onTouchMove(e) {
    void e;
  },
  onTouchEnd(e) {
    void e;
  },
  onTouchCancel(e) {
    void e;
  },
  onImeChange(e) {
    this.imeValue = (e && e.value) || '';
  },
  onImeConfirm() {
    this.imeValue = '';
  }
};
</script>
EOF

  if [ "${HAS_WASM}" -eq 1 ]; then
    cp "${WASM_STAGE}/euv_example_bg.wasm" "${out_dir}/src/Common/euv_app.wasm"
  fi

  if [ "${SHELL_ONLY}" -eq 0 ] && command -v hap >/dev/null 2>&1; then
    log_info "Building QuickApp .rpk bundle (${v}) via hap-toolkit..."
    (cd "${out_dir}" && hap release) || log_warn "hap release skipped for ${v}; source project generated in ${out_dir}"
  else
    log_info "Generated QuickApp project (${v}, package=${pkg_id}) in ${out_dir}"
  fi
}

for target in "${TARGETS[@]}"; do
  case "${target}" in
    alliance)
      emit_quickapp_project "alliance" "vip.ltpp.euv.quickapp" 1100
      ;;
    huawei)
      emit_quickapp_project "huawei" "vip.ltpp.euv.huawei.quickapp" 1100
      ;;
    *)
      log_error "Unsupported QuickApp vendor: ${target} (expected alliance|huawei|all)"
      exit 1
      ;;
  esac
done
