# ==============================================================================
# Stage 1: Build Frontend (Next.js)
# ==============================================================================
FROM node:20-slim AS frontend-builder
WORKDIR /app/frontend

# Install dependencies
COPY frontend/package*.json ./
RUN npm ci

# Copy source and build
COPY frontend/ .
# Disable telemetry during build
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build

# ==============================================================================
# Stage 2: Final Image (Python + Node.js Runtime)
# ==============================================================================
FROM python:3.11-slim

# Build Arguments for Tunnel
ARG BASTION_URL="https://bastion.3prism.ai"
ARG HOST_ARCH="amd64"

# 1. Install System Dependencies & Node.js (for runtime)
# We need Node.js to run the Next.js production server (npm start)
RUN apt-get update && apt-get install -y \
    curl \
    nodejs \
    npm \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# 2. Install Python Backend Dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 3. Bake in Portwarden Client (The "Tunnel")
# This runs during build time to download the binary into the image
RUN echo "Downloading Portwarden Client from: ${BASTION_URL}/releases/portwardenc-${HOST_ARCH}" && \
    curl -fsSL "${BASTION_URL}/releases/portwardenc-${HOST_ARCH}" -o /usr/local/bin/portwardenc && \
    chmod +x /usr/local/bin/portwardenc

# 4. Copy Frontend Build Artifacts
# We need package.json to run 'npm start'
COPY frontend/package*.json ./frontend/
# Copy the built .next folder and public assets
COPY --from=frontend-builder /app/frontend/.next ./frontend/.next
COPY --from=frontend-builder /app/frontend/public ./frontend/public
# Install ONLY production dependencies for frontend
WORKDIR /app/frontend
RUN npm ci --only=production

# 5. Copy Backend & Application Code
WORKDIR /app
COPY backend/ ./backend/
COPY *.py ./
COPY *.sh ./
COPY entrypoint.sh /usr/local/bin/

# Make scripts executable
RUN chmod +x /usr/local/bin/entrypoint.sh ./start_app.sh

# Environment Variables Defaults
ENV PW_LOCAL_PORT=3000
# Disable Next.js Telemetry
ENV NEXT_TELEMETRY_DISABLED=1

# Expose ports? 
# Technically tunnel needs NO EXPOSE, but for local debugging we might want it.
# EXPOSE 3000 8000

# Entrypoint & Command
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
# We need a robust start script for prod. 
# For now, we'll use a modified start command inline or assume start_app.sh is smart enough.
# Let's override the default start_app.sh behavior to use production modes if possible, 
# OR just keep it simple as user requested "built-in".
CMD ["bash", "-c", "cd frontend && npm start & cd backend && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
