# Stage 1: Build frontend
FROM node:20-alpine AS frontend-build

WORKDIR /frontend
COPY frontend/package*.json ./
RUN npm install
COPY frontend/ .
RUN npm run build

# Stage 2: Python backend with frontend static files
FROM python:3.11-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    libpq-dev \
    gosu \
    && rm -rf /var/lib/apt/lists/*

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

# Copy backend application
COPY backend/ .

# Copy built frontend from Stage 1
COPY --from=frontend-build /frontend/dist /app/static

# Copy and set up entrypoint script
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Create data directories
RUN mkdir -p /data/downloads /data/config /data/cookies

# Create non-root user (entrypoint will switch to this user after fixing permissions)
RUN useradd -m -u 1000 appuser && \
    chown -R appuser:appuser /app /data

EXPOSE 8080

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["hypercorn", "app.main:app", "--bind", "0.0.0.0:8080"]
