#!/bin/sh
set -eu

cd /app

sh tools/init_runtime_data.sh

python3 tools/device_mapper.py build
python3 tools/export_mysql_seed.py

MYSQL_AUTO_LOAD_EFFECTIVE="$(python3 - <<'PY'
import json
import os
from pathlib import Path

data_root = Path(os.environ.get("MOBILEMODELS_DATA_ROOT", "/data"))
config_path = data_root / "state/mysql_settings.json"
raw_default = os.environ.get("MYSQL_AUTO_LOAD", "0").strip().lower()
value = raw_default in {"1", "true", "yes", "on"}

try:
    if config_path.exists():
        payload = json.loads(config_path.read_text(encoding="utf-8"))
        raw = payload.get("auto_load", value) if isinstance(payload, dict) else value
        value = raw if isinstance(raw, bool) else str(raw).strip().lower() in {"1", "true", "yes", "on"}
except Exception:
    pass

print("1" if value else "0")
PY
)"

if [ "$MYSQL_AUTO_LOAD_EFFECTIVE" = "1" ]; then
  python3 tools/load_mysql_seed.py
else
  echo "Skipping MySQL load because MYSQL_AUTO_LOAD=$MYSQL_AUTO_LOAD_EFFECTIVE"
fi

exec python3 tools/web_server.py --host 0.0.0.0 --port 8123
