# polymodel development commands

set dotenv-load := false

# Canonical SQLite database URL for the projection store and the compile-time
# `query!` macros. Scoping it here (rather than via .env) keeps `just` recipes
# hermetic — see `set dotenv-load := false` above.
db-url := 'sqlite:./data/polymodel.db'

default:
    @just --list

# Format Rust sources. Run clippy/check separately; clippy --fix can corrupt RSX.
fix:
    cargo fmt --all
# Run clippy without --fix; automatic clippy rewrites can corrupt Dioxus RSX.
lint:
    cargo clippy --workspace --all-targets -- -D warnings -A clippy::useless_format
    cargo clippy -p polymodel --all-targets --features server -- -D warnings -A clippy::useless_format
    cargo clippy -p polymodel --target wasm32-unknown-unknown --features web -- -D warnings -A clippy::useless_format
# Compile checks across the whole workspace plus the app's server/wasm targets.
# The server check resolves compile-time `query!` macros against the committed
# `.sqlx` offline cache; regenerate it with `just sqlx-prepare` after changing
# SQL or migrations.
check:
    cargo check --workspace
    cargo check -p polymodel --features server
    cargo check -p polymodel --target wasm32-unknown-unknown --features web
    RUSTFLAGS='--cfg getrandom_backend="wasm_js"' cargo check -p polymodel-renderer-worker --target wasm32-unknown-unknown

# Create and migrate the SQLite projection database.
# Required when regenerating the `.sqlx` cache, and re-run after editing migrations.
migrate:
    mkdir -p ./data
    cargo sqlx migrate run --source migrations --database-url '{{ db-url }}'

# Regenerate the committed `.sqlx` offline query cache after changing SQL.
# Self-contained: migrates the local database first, then points `cargo sqlx
# prepare` at it via DATABASE_URL so no manual env setup is required.
sqlx-prepare: migrate
    DATABASE_URL='{{ db-url }}' cargo sqlx prepare -- -p polymodel --features server

# Run unit tests across the workspace.
test:
    cargo nextest run --workspace

# Run server-feature tests (app only; polymodel-api has no server feature).
test-server:
    cargo nextest run -p polymodel --features server

# Run browser-backed wasm tests for the renderer worker.
test-renderer:
    RUSTFLAGS='--cfg getrandom_backend="wasm_js"' cargo test -p polymodel-renderer-worker --target wasm32-unknown-unknown

# Run all local validation expected before review.
test-all: fix check lint test test-server test-renderer
# Run browser end-to-end tests.
e2e:
    cd e2e && npm test
# Start the Dioxus dev server. Builds the renderer worker first if missing.
serve *ARGS:
    @if [ ! -f public/renderer_worker_bg.wasm ] || [ ! -f public/renderer_worker_loader.js ]; then echo "renderer worker not built — running just build-renderer-worker"; just build-renderer-worker; fi
    dx serve {{ ARGS }}

# Build the renderer worker WASM bundle (separate from the app WASM).
build-renderer-worker:
    RUSTFLAGS='--cfg getrandom_backend="wasm_js"' cargo build -p polymodel-renderer-worker --bin renderer_worker --target wasm32-unknown-unknown --profile worker-release
    wasm-bindgen target/wasm32-unknown-unknown/worker-release/renderer_worker.wasm --target web --out-dir public --no-typescript
    @if command -v wasm-opt &>/dev/null; then wasm-opt public/renderer_worker_bg.wasm -O4 --enable-bulk-memory --enable-simd --enable-nontrapping-float-to-int --enable-sign-ext -o public/renderer_worker_bg.wasm; else echo "wasm-opt not found, skipping optimization"; fi

# Build and stage the single-threaded OpenCascade.js STEP conversion artifacts.
build-opencascade-step:
    node tools/renderer-step/build-and-stage-opencascade.mjs

# Build the Dioxus app for web (includes renderer worker build).
build-web: build-renderer-worker
    dx build --platform web

# Build the Dioxus app for web (release, optimized). Strips debug symbols and runs wasm-opt.
build-web-release: build-renderer-worker build-opencascade-step
    #!/usr/bin/env bash
    set -e
    dx build --platform web --release --debug-symbols=false
    if command -v wasm-opt &>/dev/null; then
        WASM=$(find target/dx/polymodel/release/web/public -name "polymodel_bg*.wasm" -print -quit 2>/dev/null)
        if [ -n "$WASM" ]; then
            echo "==> Running wasm-opt on $WASM"
            BEFORE=$(stat -c%s "$WASM")
            wasm-opt "$WASM" -Oz --enable-bulk-memory --enable-simd --enable-nontrapping-float-to-int --enable-sign-ext -o "$WASM" || { echo "==> wasm-opt failed, keeping unoptimized wasm"; exit 0; }
            AFTER=$(stat -c%s "$WASM")
            echo "    $BEFORE -> $AFTER bytes"
        fi
    else
        echo "==> wasm-opt not found, skipping optimization"
    fi

# Verify the renderer split: no heavy deps in the app, worker wasm exists, bundle size under ceiling.
verify-renderer-split: build-web
    @echo "==> AC.1: checking app dependency tree for forbidden crates..."
    @if cargo tree -p polymodel --target wasm32-unknown-unknown --features web --edges normal 2>/dev/null | grep -qE '(^| )three-d v|three-d-asset v|stl_io v|polymodel-mesh v'; then echo "FAIL: forbidden crate found in app dependency tree"; exit 1; else echo "PASS: no forbidden crates"; fi
    @echo "==> AC.1b: checking app Cargo.toml for forbidden deps..."
    @if grep -qE '^\s*(three-d|three-d-asset|stl_io|polymodel-mesh)\b' Cargo.toml; then echo "FAIL: forbidden dep found in Cargo.toml"; exit 1; else echo "PASS: no forbidden deps in Cargo.toml"; fi
    @echo "==> AC.2: checking app wasm bundle size (debug build, debuginfo-dominated)..."
    @APP_WASM="target/dx/polymodel/debug/web/public/wasm/polymodel_bg.wasm" && test -f "$APP_WASM" && SIZE=$(stat -c%s "$APP_WASM") && echo "app wasm: $SIZE bytes" && test "$SIZE" -lt 134217728 && echo "PASS: app wasm < 128MB ceiling" || { echo "FAIL: app wasm >= 128MB or not found"; exit 1; }
    @echo "==> AC.2b: checking worker wasm exists..."
    @test -f public/renderer_worker_bg.wasm && echo "PASS: worker wasm exists" || { echo "FAIL: worker wasm not found"; exit 1; }
    @echo "==> All renderer-split checks passed."

# Regenerate crates/polymodel-api from authored lexicons via the local Jacquard checkout.
generate-api:
    nix run ../jacquard
# Create a sibling jj workspace for a Jira ticket or feature slug, then start a fresh change.
workspace-create name:
    root="$(jj workspace root)" && workspace_path="$(dirname "$root")/{{ name }}" && jj workspace add "$workspace_path" -r @
    root="$(jj workspace root)" && workspace_path="$(dirname "$root")/{{ name }}" && cd "$workspace_path" && jj desc -m "{{ name }}"

# List jj workspaces.
workspace-list:
    jj workspace list

# Forget a jj workspace after the work is safely landed or intentionally abandoned.
workspace-forget name:
    jj workspace forget {{ name }}

# Show current jj state and diff.
status:
    jj status
    jj diff --summary

# Clean build artifacts.
clean:
    cargo clean
    rm -rf target/dx
