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

if [[ $# -lt 1 ]]; then
  echo "Usage: $0 <repo-root> [app-name]"
  echo "Example: $0 ~/Code/trader-app Trader"
  exit 1
fi

REPO_ROOT="$1"
APP_NAME="${2:-WebShellApp}"

mkdir -p "$REPO_ROOT/web/src"
mkdir -p "$REPO_ROOT/web/src/web_core"
mkdir -p "$REPO_ROOT/web/src/tests"
mkdir -p "$REPO_ROOT/mac/src/App/EmbeddedBackend"
mkdir -p "$REPO_ROOT/mac/src/App/Help"
mkdir -p "$REPO_ROOT/mac/src/AppTests"
mkdir -p "$REPO_ROOT/mac/src/AppUITests"
mkdir -p "$REPO_ROOT/scripts"
mkdir -p "$REPO_ROOT/docs"

cat > "$REPO_ROOT/docs/architecture.md" <<DOC
# ${APP_NAME} Architecture

- web backend source: ./web/src
- mac shell source: ./mac/src
- embedded backend binary: ./mac/src/App/EmbeddedBackend/WebBackend
- native help page: ./mac/src/App/Help/help.html
DOC

cat > "$REPO_ROOT/scripts/README.build.md" <<DOC
# Build Script Placeholders

Add:
- build_embedded_backend.sh
- build_selfcontained_mac_app.sh
- create_installer_dmg.sh

Suggested script behaviors:
- Discover \`*.xcodeproj\` under \`mac/src\` unless \`MAC_PROJECT_PATH\` is provided.
- Discover scheme via \`xcodebuild -list -json\` unless \`MAC_SCHEME\` is provided.
- Default backend binary name: \`WebBackend\` (override with \`BACKEND_BIN_NAME\`).
- Write DMG artifacts to \`build/dmg/\`.
DOC

cat > "$REPO_ROOT/web/src/ONBOARDING.md" <<DOC
# ${APP_NAME} Onboarding

Add your web help/onboarding content here.
DOC

cat > "$REPO_ROOT/mac/src/App/Help/help.html" <<DOC
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Help</title>
  </head>
  <body>
    <h1>${APP_NAME} Help</h1>
    <p>Replace this with your quick start and onboarding content.</p>
  </body>
</html>
DOC

cat > "$REPO_ROOT/web/run.sh" <<'DOC'
#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VENV_DIR="$ROOT_DIR/.venv"
WEB_SRC_DIR="$ROOT_DIR/web/src"

if [[ ! -d "$VENV_DIR" ]]; then
  python3 -m venv "$VENV_DIR"
fi

# shellcheck disable=SC1091
source "$VENV_DIR/bin/activate"
pip install -r "$WEB_SRC_DIR/requirements.txt"
exec streamlit run "$WEB_SRC_DIR/app.py"
DOC
chmod +x "$REPO_ROOT/web/run.sh"

touch "$REPO_ROOT/.gitignore"
for line in "build/" "*.dmg" "rw.*.dmg"; do
  if ! grep -Fxq "$line" "$REPO_ROOT/.gitignore"; then
    printf "%s\n" "$line" >> "$REPO_ROOT/.gitignore"
  fi
done

echo "Created layout for ${APP_NAME}:"
echo "- $REPO_ROOT/web/src"
echo "- $REPO_ROOT/mac/src"
echo "- $REPO_ROOT/scripts"
echo "- $REPO_ROOT/docs"
echo "- $REPO_ROOT/.gitignore (updated with build/DMG ignore rules)"
