# Multi-stage Dockerfile for ARM64 optimization
# Stage 1: Build dependencies + PyArmor obfuscation
FROM python:3.11-slim-bullseye as builder

# Install system dependencies for building
RUN apt-get update && apt-get install -y \
    build-essential \
    curl \
    && rm -rf /var/lib/apt/lists/*

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

# Copy requirements and install Python dependencies + PyArmor
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt && \
    pip install --no-cache-dir pyarmor

# Copy application code for obfuscation
COPY . /build
WORKDIR /build

# Fix CRLF + register license + obfuscate
# Skip if WAOUW_SKIP_OBFUSCATION=1 (for development/debugging)
ARG WAOUW_SKIP_OBFUSCATION=0
RUN find /build -name "*.py" -exec sed -i 's/\r$//' {} + && \
    find /build -name "*.sh" -exec sed -i 's/\r$//' {} + && \
    if [ "$WAOUW_SKIP_OBFUSCATION" != "1" ]; then \
        bash /build/obfuscate.sh 2>&1 || echo "Obfuscation failed, continuing with plain .py"; \
    fi

# Production stage
FROM python:3.11-slim-bullseye

# Install runtime dependencies (curl, Docker CLI for exec, SMB/NFS for backup)
RUN apt-get update && apt-get install -y \
    curl \
    cifs-utils \
    nfs-common \
    ca-certificates \
    gnupg \
    && install -m 0755 -d /etc/apt/keyrings \
    && curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg \
    && echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian bullseye stable" > /etc/apt/sources.list.d/docker.list \
    && apt-get update && apt-get install -y docker-ce-cli \
    && rm -rf /var/lib/apt/lists/*

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

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

# Set working directory
WORKDIR /app

# Copy obfuscated application code from builder
COPY --from=builder --chown=waouw:waouw /build .

# Remove build artifacts and Docker marker (PyArmor license check)
RUN rm -f compile_cython.py obfuscate.sh pyarmor-regkey.txt && \
    rm -rf build/ __pycache__/ && \
    find . -name "*.c" -delete && \
    find . -name "_cython_setup_*" -delete && \
    rm -f /.dockerenv

# Create directories for logs and data
RUN mkdir -p /app/logs /app/data /data/backups && \
    chown -R waouw:waouw /app /data/backups

# Switch to non-root user
USER waouw

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

# Expose port
EXPOSE 8000

# Start application
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
