# Pololu Tic T249 Motor Controller - Dockerfile
# Multi-stage build for smaller image size

FROM python:3.11-slim-bookworm as builder

# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    libusb-1.0-0-dev \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Create virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Install Python dependencies
COPY pyproject.toml ./
RUN pip install --upgrade pip && \
    pip install build && \
    pip install ticlib pyusb flask python-dotenv

# Production stage
FROM python:3.11-slim-bookworm as production

# Install runtime dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    libusb-1.0-0 \
    udev \
    && rm -rf /var/lib/apt/lists/*

# Copy virtual environment from builder
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Create non-root user
RUN groupadd -r pololu && useradd -r -g pololu pololu

# Set working directory
WORKDIR /app

# Copy application code
COPY web_panel.py ./
COPY detect_usb.py ./
COPY tic_t249_controller.py ./
COPY config.json ./
COPY templates/ ./templates/
COPY .env.example ./

# Create .env file from example if not exists
RUN cp .env.example .env

# Install udev rules
RUN echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="1ffb", MODE="0666", GROUP="plugdev"' > /etc/udev/rules.d/99-pololu-tic.rules

# Expose port
EXPOSE 5000

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

# Switch to non-root user
USER pololu

# Run web panel
CMD ["python", "web_panel.py"]
