# PANJIT Document Translator - Production Dockerfile
# Multi-stage build for optimized production image

# Stage 1: Frontend build
FROM node:18-alpine AS frontend-builder

WORKDIR /app/frontend

# Copy package files
COPY frontend/package*.json ./

# Install dependencies (including dev dependencies for build)
RUN npm ci

# Copy source files (excluding node_modules)
COPY frontend/src ./src
COPY frontend/public ./public
COPY frontend/index.html ./
COPY frontend/vite.config.js ./
COPY frontend/auto-imports.d.ts ./

# Build frontend
RUN npm run build

# Stage 2: Python production image
FROM python:3.11-slim

# Set working directory
WORKDIR /app

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    FLASK_ENV=production \
    PORT=12010

# Install system dependencies including Redis
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    curl \
    redis-server \
    && rm -rf /var/lib/apt/lists/*

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

# Copy application code
COPY app/ ./app/
COPY *.py ./

# Copy configuration files
COPY .env ./
COPY api.txt ./

# Copy batch scripts (for reference)
COPY *.bat ./scripts/

# Copy frontend build output
COPY --from=frontend-builder /app/frontend/dist ./static

# Create required directories
RUN mkdir -p uploads logs scripts

# Create startup script
RUN echo '#!/bin/bash' > /app/start.sh && \
    echo 'redis-server --daemonize yes' >> /app/start.sh && \
    echo 'sleep 2' >> /app/start.sh && \
    echo 'celery -A celery_app worker --loglevel=info --pool=solo --detach' >> /app/start.sh && \
    echo 'python app.py' >> /app/start.sh && \
    chmod +x /app/start.sh

# Set permissions
RUN useradd -m -u 1000 appuser && \
    chown -R appuser:appuser /app && \
    chmod -R 755 /app

# Switch to non-root user
USER appuser

# Expose port
EXPOSE 12010

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

# Start application with Redis and Celery
CMD ["/app/start.sh"]