# Multi-stage build to create a minimal image
FROM python:3.13-slim AS builder

# Create working directory
WORKDIR /app

# Install tools needed for Tailwind CSS build
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Copy dependency files
COPY requirements.txt ./

# Install dependencies to a target directory
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --no-deps --disable-pip-version-check -r requirements.txt

# Build Tailwind CSS
COPY index.html style-input.css tailwind.config.js ./
RUN curl -sL https://github.com/tailwindlabs/tailwindcss/releases/download/v3.4.17/tailwindcss-linux-x64 -o tailwindcss \
    && chmod +x tailwindcss \
    && ./tailwindcss -i ./style-input.css -o ./style.css --minify

# Runtime stage
FROM python:3.13-slim AS runtime

# Create working directory
WORKDIR /app

# Install only runtime dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Create a non-root user for security
RUN useradd --home-dir /app --no-create-home --uid 1000 myice

# Copy installed packages from builder stage
COPY --from=builder /usr/local/lib/python3.13/site-packages /usr/local/lib/python3.13/site-packages

# Copy application code and compiled assets
COPY index.html favicon.ico ./
COPY --from=builder /app/style.css ./style.css
COPY myice ./myice

# Change ownership of copied files
RUN chown -R myice:myice /app

# Switch to non-root user
USER myice

# Bytecompile Python files for faster first load
RUN python -m compileall -q ./myice

# Expose port
EXPOSE 8000

# Run the application
ENTRYPOINT ["python", "-m", "uvicorn", "myice.webapi:app", "--host", "0.0.0.0", "--port", "8000"]
