# ============================================
# Stage 1: Build React frontend
# ============================================
FROM node:20-alpine AS frontend-builder

WORKDIR /build

# Copy frontend package files
COPY web/web-app/package.json web/web-app/package-lock.json ./

# Install dependencies
RUN npm ci

# Copy frontend source
COPY web/web-app/ ./

# Build production bundle
RUN npm run build

# ============================================
# Stage 2: Python server
# ============================================
FROM python:3.11-slim AS server

# Install system dependencies for yt-dlp/ffmpeg/deno
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    ffmpeg \
    ca-certificates \
    unzip \
    git \
    && rm -rf /var/lib/apt/lists/* && \
    curl -fsSL https://deno.land/install.sh | sh && \
    ln -s /root/.deno/bin/deno /usr/local/bin/deno

WORKDIR /app

# Copy Python requirements first for better caching
COPY requirements.txt requirements-api.txt ./
COPY web/requirements-web.txt ./requirements-web.txt

# Install Python dependencies, yt-dlp nightly for latest YouTube patches
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt && \
    pip install --no-cache-dir -r requirements-api.txt && \
    pip install --no-cache-dir -r requirements-web.txt && \
    pip install --no-cache-dir --upgrade "yt-dlp[default] @ git+https://github.com/yt-dlp/yt-dlp.git"

# Copy application code
COPY . .

# Copy built frontend from stage 1
COPY --from=frontend-builder /build/dist web/web-app/dist

# Create download and config directories
RUN mkdir -p /downloads /app/.config/youtube_cli/logs

# Set environment variables
ENV PYTHONUNBUFFERED=1
ENV PORT=4096
ENV DOWNLOAD_DIR=/downloads
ENV CONFIG_DIR=/app/.config/youtube_cli
ENV DOCKER=true

# Expose port
EXPOSE 4096

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

# Run the application
WORKDIR /app/web/server
CMD ["python", "app.py"]