#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT"

command -v python3 >/dev/null || { echo "Python 3.10+ is required." >&2; exit 1; }
python3 - <<'PY'
import sys
if sys.version_info < (3,10):
    raise SystemExit('Python 3.10+ is required')
PY

python3 -m venv .venv
rm -f .venv/.kimu-runtime-ready
PIP=(.venv/bin/python -m pip --disable-pip-version-check --no-input)
WHEELHOUSE="${KIMU_WHEELHOUSE:-$ROOT/vendor/python-wheels}"
INSTALL_ARGS=()
if [[ -d "$WHEELHOUSE" ]] && find "$WHEELHOUSE" -maxdepth 1 -type f \( -name '*.whl' -o -name '*.tar.gz' \) -print -quit | grep -q .; then
  INSTALL_ARGS+=(--no-index --find-links "$WHEELHOUSE")
  echo "Using local Python dependency wheelhouse: $WHEELHOUSE"
fi

if ! "${PIP[@]}" install "${INSTALL_ARGS[@]}" -r requirements.txt; then
  cat >&2 <<'EOF'
KIMU runtime dependency installation failed.

The application source and static/core verification remain usable, but Flask cannot start until
all packages in requirements.txt are installed. On an online target run ./install.sh again, or
place compatible wheels in vendor/python-wheels and rerun with:

  KIMU_WHEELHOUSE=/path/to/wheels ./install.sh
EOF
  PYTHONPATH=src python3 scripts/check.py || true
  exit 2
fi
touch .venv/.kimu-runtime-ready

if [[ ! -f .env ]]; then
  readarray -t GENERATED < <(python3 - <<'PY'
import base64
import os
import secrets
print(secrets.token_urlsafe(48))
print(base64.urlsafe_b64encode(os.urandom(32)).decode('ascii'))
PY
)
  SECRET="${GENERATED[0]}"
  MASTER_KEY="${GENERATED[1]}"
  cp .env.example .env
  python3 - "$SECRET" "$MASTER_KEY" <<'PY'
from pathlib import Path
import sys
p=Path('.env')
t=p.read_text()
t=t.replace('KIMU_SECRET_KEY=', 'KIMU_SECRET_KEY='+sys.argv[1], 1)
t=t.replace('KIMU_MASTER_KEY=', 'KIMU_MASTER_KEY='+sys.argv[2], 1)
p.write_text(t)
PY
  chmod 600 .env
fi
mkdir -p instance instance/files
chmod 700 instance instance/files
PYTHONPATH=src .venv/bin/python scripts/init_db.py
PYTHONPATH=src .venv/bin/python scripts/check.py
PYTHONPATH=src .venv/bin/python -m unittest discover -s tests -v
printf '\nInstalled KIMU Increment 46 Runtime Hardening and all available workflow tests passed.\nEdit .env, set TOGETHER_API_KEY, and use KIMU_COOKIE_SECURE=1 behind HTTPS for Conversation Mode.\nBack up KIMU_MASTER_KEY securely; stored file bodies cannot be recovered without it.\nFor K2.7 Coder, set KIMU_K27_MODEL_ID and KIMU_K27_CONFIGURED=1; then verify Whisper/Sonic WebSockets and barge-in on the target Android device.\nRun: ./run.sh\nOpen: http://127.0.0.1:19460\n'
