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

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
FRONTEND="$ROOT/frontend"
OUT="$ROOT/ios/WordLoop/WordLoop/www"

echo ">>> 构建 iOS 内嵌前端"
cd "$FRONTEND"
if [ ! -d node_modules ]; then
  npm install --silent
fi
npm run build:ios

rm -rf "$OUT"
mkdir -p "$OUT"
cp -R dist/* "$OUT/"

python3 - <<PY
from pathlib import Path

out = Path("$OUT")
html_path = out / "index.html"
js_path = out / "assets" / "app.js"
css_path = out / "assets" / "app.css"
html = html_path.read_text(encoding="utf-8")
js = js_path.read_text(encoding="utf-8")
css = css_path.read_text(encoding="utf-8")

# 单文件内联，避免 wordloop:// 二次请求脚本失败
html = html.replace('<link rel="stylesheet" href="wordloop://app/assets/app.css">', f"<style>{css}</style>")
html = html.replace(
    '<script src="wordloop://app/assets/app.js"></script>',
    "",
)
# 脚本放在 </body> 前，确保 #app 已存在（head 内联会导致 Vue mount 失败、白屏）
html = html.replace(
    "</body>",
    f"    <script>{js}</script>\\n  </body>",
)

html_path.write_text(html, encoding="utf-8")
print(">>> 已内联 app.js / app.css 到 index.html")
PY

echo ">>> 已复制到 $OUT"
