# Use an official Python runtime as base image
FROM python:3.11-slim

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    DEBIAN_FRONTEND=noninteractive

# Install system dependencies including Samba tools
RUN apt-get update && apt-get install -y \
    samba \
    samba-common-bin \
    samba-dsdb-modules \
    winbind \
    libldap2-dev \
    libsasl2-dev \
    libssl-dev \
    krb5-user \
    build-essential \
    pkg-config \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Create app directory
WORKDIR /app

# Copy requirements first to leverage Docker cache
COPY requirements.txt .

# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Create non-root user
RUN useradd --create-home --shell /bin/bash app && \
    chown -R app:app /app

# Copy application code
COPY src/ ./src/
COPY main.py .
COPY start.sh .

# Copy SSL certificates
COPY ssl/ ./ssl/

# Set ownership and make start script executable
RUN chown -R app:app /app && chmod +x /app/start.sh

# Switch to non-root user
USER app

# Expose ports
EXPOSE 8000
EXPOSE 8443

# Health check (will try HTTPS first, then HTTP)
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -k -f https://localhost:8443/health || curl -f http://localhost:8000/health || exit 1

# Run the startup script
CMD ["/app/start.sh"]