# Stage 1 — Build WASM from Rust
FROM rust:1.85-bookworm AS wasm-builder

# Install wasm-pack via pre-built binary (much faster than cargo install)
RUN curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

WORKDIR /app

# Copy workspace Cargo.toml
COPY Cargo.toml ./

# Copy the crates we actually need to compile
COPY calcpad-engine/ calcpad-engine/
COPY calcpad-wasm/ calcpad-wasm/

# Create stub Cargo.toml + src for workspace members we don't need to build.
# The workspace requires all members to exist, but we never compile these.
RUN mkdir -p calcpad-cli/src && \
    printf '[package]\nname = "calcpad-cli"\nversion = "0.1.0"\nedition = "2021"\n\n[[bin]]\nname = "calcpad"\npath = "src/main.rs"\n\n[dependencies]\ncalcpad-engine = { path = "../calcpad-engine" }\n' > calcpad-cli/Cargo.toml && \
    echo 'fn main() {}' > calcpad-cli/src/main.rs && \
    mkdir -p calcpad-windows/src && \
    printf '[package]\nname = "calcpad-windows"\nversion = "0.1.0"\nedition = "2021"\n\n[[bin]]\nname = "calcpad-win"\npath = "src/main.rs"\n' > calcpad-windows/Cargo.toml && \
    echo 'fn main() {}' > calcpad-windows/src/main.rs

# Build WASM
RUN wasm-pack build calcpad-wasm --target web --release

# Stage 2 — Build frontend with Vite
FROM node:22-slim AS web-builder

WORKDIR /app/calcpad-web

# Install dependencies first (layer caching)
COPY calcpad-web/package.json calcpad-web/package-lock.json* ./
RUN npm install

# Copy web source
COPY calcpad-web/ ./

# Copy WASM output into public/wasm/ so Vite includes it in the build
COPY --from=wasm-builder /app/calcpad-wasm/pkg/calcpad_wasm.js public/wasm/calcpad_wasm.js
COPY --from=wasm-builder /app/calcpad-wasm/pkg/calcpad_wasm_bg.wasm public/wasm/calcpad_wasm_bg.wasm

# Build (skip tsc type-check — that belongs in CI, not Docker)
RUN npx vite build

# Stage 3 — Serve with nginx
FROM nginx:1.27-alpine

COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=web-builder /app/calcpad-web/dist /usr/share/nginx/html

EXPOSE 8080

CMD ["nginx", "-g", "daemon off;"]
