# Build stage
FROM ubuntu:20.04 AS builder

# Set environment variables to avoid interactive prompts
ENV DEBIAN_FRONTEND=noninteractive \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

# Configure apt to use reliable mirrors
RUN echo "deb http://archive.ubuntu.com/ubuntu focal main restricted universe" > /etc/apt/sources.list && \
    echo "deb http://archive.ubuntu.com/ubuntu focal-updates main restricted universe" >> /etc/apt/sources.list && \
    echo "deb http://archive.ubuntu.com/ubuntu focal-security main restricted universe" >> /etc/apt/sources.list && \
    echo "deb http://us.archive.ubuntu.com/ubuntu focal main restricted universe" >> /etc/apt/sources.list

# Install Python 3.9 and build dependencies
RUN apt-get update -o Acquire::Retries=10 -o Acquire::http::Timeout=30 && \
    apt-get install -y --no-install-recommends \
    python3.9 \
    python3.9-dev \
    python3-pip \
    gcc \
    g++ \
    make && \
    rm -rf /var/lib/apt/lists/*

# Configure pip to use a reliable mirror and increase timeouts
RUN python3 -m pip install --no-cache-dir --upgrade pip && \
    pip config set global.index-url https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple && \
    pip config set install.timeout 60 && \
    pip config set install.retries 5

# Install MkDocs and plugins
RUN pip install --no-cache-dir \
    mkdocs==1.6.1 \
    mkdocs-material==9.5.39 \
    mkdocs-macros-plugin==1.2.0 \
    mkdocs-minify-plugin==0.8.0 \
    mkdocs-awesome-pages-plugin==2.9.2 \
    mkdocs-glightbox==0.4.0

# Set working directory
WORKDIR /docs

# Copy configuration and docs
COPY mkdocs.yml .
COPY docs/ ./docs/

# Build the static site with strict mode
RUN mkdocs build 

# Runtime stage
FROM ubuntu:20.04

# Set environment variables
ENV DEBIAN_FRONTEND=noninteractive \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

# Install Python 3.9 minimal for runtime
RUN apt-get update -o Acquire::Retries=10 -o Acquire::http::Timeout=30 && \
    apt-get install -y --no-install-recommends \
    python3.9 \
    curl && \
    rm -rf /var/lib/apt/lists/* && \
    ln -sf /usr/bin/python3.9 /usr/bin/python3

# Set working directory
WORKDIR /site

# Copy the built site from the builder stage
COPY --from=builder /docs/site .

# Expose port 80
EXPOSE 80

# Healthcheck to ensure the server is running
HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost:80/ || exit 1

# Serve the static site with Python's http.server
CMD ["python3", "-m", "http.server", "80"]