# --- STAGE 1: Build Stage ---
FROM python:3.12-slim AS builder

# Install uv from the official binary
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

# Set the working directory
WORKDIR /app

# Enable bytecode compilation for faster startups
ENV UV_COMPILE_BYTECODE=1

# Copy only dependency files first to leverage Docker layer caching
COPY pyproject.toml uv.lock ./

# Install dependencies into a virtual environment (.venv)
# --frozen ensures it matches your uv.lock exactly
# --no-install-project skips installing the current project code in this step
RUN uv sync --frozen --no-install-project --no-dev

# --- STAGE 2: Runtime Stage ---
FROM python:3.12-slim

# Set the working directory
WORKDIR /app

# Copy the virtual environment from the builder stage
COPY --from=builder /app/.venv /app/.venv

# Copy the actual application package and configuration
# Note: We copy src/uv_style to /app/uv_style to preserve the package name
COPY src/uv_style ./uv_style
COPY pyproject.toml ./

# Environment Variables:
# 1. Add the venv to the PATH so gunicorn/python work naturally
# 2. Add /app to PYTHONPATH so Python finds the 'uv_style' folder as a module
ENV PATH="/app/.venv/bin:$PATH"
ENV PYTHONPATH="/app"
ENV PYTHONUNBUFFERED=1

# Security: Run as a non-privileged user
RUN useradd -m appuser && chown -R appuser:appuser /app
USER appuser

# Document the port
EXPOSE 5000

# Start Gunicorn
# 'uv_style.main:app' maps to: Folder 'uv_style' -> File 'main.py' -> Variable 'app'
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "4", "uv_style.main:app"]