# ---------- BUILD STAGE ----------
FROM python:3.12-slim AS builder

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

# Use mirror
# RUN rm -rf /etc/apt/sources.list.d/* && \
#     echo "deb http://mirror.arvancloud.ir/debian bookworm main contrib main" > /etc/apt/sources.list && \
#     echo "deb http://mirror.arvancloud.ir/debian bookworm-updates main contrib main" >> /etc/apt/sources.list && \
#     echo "deb http://mirror.arvancloud.ir/debian-security bookworm-security main contrib main" >> /etc/apt/sources.list && \
#     echo 'Acquire::Check-Valid-Until "false";' > /etc/apt/apt.conf.d/99no-check-valid-until

# Build deps
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY requirements.txt .

# Install dependencies (cached)
# RUN --mount=type=cache,target=/root/.cache/pip \
#     pip install -i https://mirror-pypi.runflare.com/simple --upgrade pip && \
#     pip install -i https://mirror-pypi.runflare.com/simple --no-cache-dir -r requirements.txt

RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt


# ---------- RUNTIME STAGE ----------
FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

# Use mirror
# RUN rm -rf /etc/apt/sources.list.d/* && \
#     echo "deb http://mirror.arvancloud.ir/debian bookworm main contrib main" > /etc/apt/sources.list && \
#     echo "deb http://mirror.arvancloud.ir/debian bookworm-updates main contrib main" >> /etc/apt/sources.list && \
#     echo "deb http://mirror.arvancloud.ir/debian-security bookworm-security main contrib main" >> /etc/apt/sources.list && \
#     echo 'Acquire::Check-Valid-Until "false";' > /etc/apt/apt.conf.d/99no-check-valid-until

# Runtime deps only
RUN apt-get update && apt-get install -y --no-install-recommends \
    libpq5 \
    netcat-openbsd \
    && rm -rf /var/lib/apt/lists/*

# Non-root user
RUN useradd -m appuser

WORKDIR /app

# Copy python deps from builder
COPY --from=builder /usr/local/lib/python3.12/site-packages \
    /usr/local/lib/python3.12/site-packages

COPY --from=builder /usr/local/bin /usr/local/bin

# Copy app source
COPY . .

USER appuser

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
