# ── Stage 1: build dashboard ──────────────────────────────────────────────────
FROM oven/bun:1 AS frontend-builder

WORKDIR /app

# Cache bun deps separately — only re-runs when bun.lockb changes
COPY dashboard/package.json dashboard/bun.lock ./dashboard/
RUN cd dashboard && bun install --frozen-lockfile

COPY dashboard/ ./dashboard/
RUN cd dashboard && bun run build
# → /app/static/dashboard/  (matches vite outDir: '../static/dashboard')

# ── Stage 2: Python runtime ───────────────────────────────────────────────────
FROM ghcr.io/astral-sh/uv:python3.14-bookworm-slim

ARG version
LABEL Version=$version
ENV build_version=$version

RUN apt-get update \
    && apt-get install -y --no-install-recommends curl \
    && apt-get upgrade -y openssl \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy \
    UV_PYTHON_DOWNLOADS=0 \
    PATH="/app/.venv/bin:$PATH" \
    UVICORN_PORT=8080

# Install Python deps — cached layer, only rebuilds when uv.lock/pyproject.toml change
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project --no-dev

# Copy source then install the project itself (separate layer for better caching)
COPY src/ ./src/
COPY migrations/ ./migrations/
COPY pyproject.toml uv.lock ./

RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked --no-dev

# Copy built frontend from stage 1
COPY --from=frontend-builder /app/static/dashboard/ ./static/dashboard/

COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

EXPOSE 8080

ENTRYPOINT ["/entrypoint.sh"]
