# Multi-stage build for smaller image size
FROM python:3.14-alpine AS python-base

# Install runtime dependencies
RUN apk add --no-cache curl

# Create non-root user for security
RUN addgroup -g 1001 -S app &&\
    adduser -u 1001 -S app -G app

# Set working directory
WORKDIR /app

#############################################
# Builder stage
#############################################
FROM python-base AS builder

# Install build dependencies needed for cryptography
RUN apk add --no-cache gcc musl-dev libffi-dev openssl-dev

# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Build Tailwind CSS
COPY templates/index.html templates/index.html
COPY style-input.css tailwind.config.js ./
RUN case "$(uname -m)" in \
        x86_64) arch="x64" ;; \
        aarch64|arm64) arch="arm64" ;; \
        *) echo "Unsupported architecture: $(uname -m)"; exit 1 ;; \
    esac \
    && curl -sL "https://github.com/tailwindlabs/tailwindcss/releases/download/v3.4.17/tailwindcss-linux-${arch}" -o tailwindcss \
    && chmod +x tailwindcss \
    && ./tailwindcss -i ./style-input.css -o ./style.css --minify

#############################################
# Final stage
#############################################
FROM python-base

# Copy installed Python packages and binaries from builder stage
COPY --from=builder /usr/local/lib/python3.14/site-packages /usr/local/lib/python3.14/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# Copy application files
COPY main.py .
COPY templates/ templates/
COPY --from=builder /app/style.css ./style.css

# Change ownership to non-root user
RUN chown -R app:app /app

# Switch to non-root user
USER app

# Expose port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# Run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]