#!/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
import re

out = Path("$OUT")
html_path = out / "index.html"
html = html_path.read_text(encoding="utf-8")

# 保持外链资源，避免把 ~1.4MB JS 内联进 HTML 导致 WebKit std::overflow_error 崩溃
html = html.replace("wordloop://app/assets/", "./assets/")

script = re.search(r'<script src="\./assets/[^"]+"></script>', html)
if script:
    tag = script.group(0)
    if tag not in html.split("</body>", 1)[-1]:
        html = html.replace(tag, "", 1)
        html = html.replace("</body>", f"    {tag}\n  </body>", 1)

html_path.write_text(html, encoding="utf-8")

if len(html) > 20_000:
    raise SystemExit("index.html 过大，可能仍含内联 JS，会导致 WebKit overflow 崩溃")
for block in re.findall(r"<script>(.*?)</script>", html, re.DOTALL):
    if len(block) > 1000:
        raise SystemExit("index.html 检测到内联业务脚本，请保持 app.js 外链")
if "./assets/app.js" not in html:
    raise SystemExit("index.html 缺少 ./assets/app.js 外链")

print(">>> 已生成外链版 index.html（app.js / app.css 独立文件）")
PY

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