# ============================================================
# STAGE 1: Builder — build wheel (Alpine, pip)
# ============================================================
FROM python:3.10-alpine AS builder

ENV PIP_ROOT_USER_ACTION=ignore \
    PIP_NO_CACHE_DIR=1

WORKDIR /build

# Build deps (C extensions for shapely et al.)
RUN apk add --no-cache build-base \
    && pip install --no-cache-dir build hatchling

COPY pyproject.toml LICENSE README.md .
COPY src/ src/

RUN python -m build --wheel --no-isolation \
    && rm -rf src/ pyproject.toml LICENSE README.md \
    && apk del build-base \
    && rm -rf /root/.cache /var/cache/apk/* /tmp/*


# ============================================================
# STAGE 2: Runtime — Alpine-based, minimal (~90–100 MB target)
# ============================================================
FROM python:3.10-alpine

LABEL org.opencontainers.image.title="nspd-mcp" \
      org.opencontainers.image.description="MCP server for Russian National Spatial Data System (НСПД)" \
      org.opencontainers.image.source="https://github.com/aptkzzz/nspd-mcp" \
      org.opencontainers.image.licenses="MIT"

# Critical size-savers + runtime config
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PYNSPD_CACHE_PATH=/app/.nspd_cache \
    PYNSPD_LOG_FORMAT=console

WORKDIR /app

# Single layer: user + cache dir + purge apk cache
RUN addgroup -S nspd && adduser -S -G nspd -h /app -s /sbin/nologin nspd \
    && mkdir -p /app/.nspd_cache && chown nspd:nspd /app/.nspd_cache \
    && rm -rf /var/cache/apk/* /tmp/*

# Copy wheel from builder
COPY --from=builder /build/dist/*.whl /tmp/

# Install, strip build-time tools, purge caches & test data
RUN set -e; \
    pip install --no-cache-dir --no-compile /tmp/*.whl; \
    rm -rf /tmp/*.whl /root/.cache; \
    # Remove pip + setuptools + wheel — not needed at runtime
    find /usr/local -type d \( -name 'pip*' -o -name 'setuptools*' -o -name 'wheel*' -o -name '__pycache__' \) -exec rm -rf {} + 2>/dev/null; \
    find /usr/local -type f \( -name '*.pyc' -o -name '*.pyo' \) -delete; \
    # Strip test dirs from numpy and other heavy packages
    find /usr/local/lib/python3.10/site-packages -type d \( -name tests -o -name test \) -exec rm -rf {} + 2>/dev/null; \
    # Remove any leftover __pycache__ after deleting test dirs
    find /usr/local -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true

EXPOSE 8000 8080

USER nspd

ENTRYPOINT ["nspd-mcp"]
