# Dockerfile for building and testing folk-runtime-embed.
#
# PHP is compiled from source with --enable-embed to produce libphp.so.
# Then Rust crate is built and tested against it.
#
# Usage:
#   docker build -f crates/folk-runtime-embed/Dockerfile -t folk-embed-test .
#   docker run --rm folk-embed-test
#
# Build context: folk-core root (so we can access all workspace crates)

# ── Stage 1: Build PHP with embed SAPI ───────────────────────────
FROM debian:bookworm-slim AS php-builder

RUN apt-get update && apt-get install -y \
    build-essential autoconf bison re2c pkg-config \
    libxml2-dev libsqlite3-dev libonig-dev libcurl4-openssl-dev \
    libssl-dev zlib1g-dev libreadline-dev \
    curl \
    && rm -rf /var/lib/apt/lists/*

ARG PHP_VERSION=8.3.15
RUN curl -fSL "https://www.php.net/distributions/php-${PHP_VERSION}.tar.xz" -o /tmp/php.tar.xz \
    && mkdir -p /usr/src/php \
    && tar xf /tmp/php.tar.xz -C /usr/src/php --strip-components=1 \
    && rm /tmp/php.tar.xz

WORKDIR /usr/src/php

RUN ./configure \
    --enable-embed=shared \
    --enable-opcache \
    --enable-mbstring \
    --enable-pcntl \
    --enable-sockets \
    --with-curl \
    --with-openssl \
    --with-zlib \
    --with-readline \
    --with-config-file-path=/etc/php \
    --with-config-file-scan-dir=/etc/php/conf.d \
    --disable-cgi \
    --disable-phpdbg \
    --prefix=/usr/local \
    && make -j"$(nproc)" \
    && make install \
    && mkdir -p /etc/php/conf.d

# Verify embed SAPI was built
RUN test -f /usr/local/lib/libphp.so && echo "libphp.so found" || (echo "FATAL: libphp.so not found" && exit 1)
RUN php-config --php-sapis | grep -q embed && echo "embed SAPI confirmed" || (echo "FATAL: embed SAPI not in php-config" && exit 1)

# ── Stage 2: Build and test Rust crate ────────────────────────────
FROM debian:bookworm-slim

# Install system deps
RUN apt-get update && apt-get install -y \
    build-essential pkg-config curl \
    libxml2 libsqlite3-0 libonig5 libcurl4 libssl3 zlib1g libreadline8 \
    && rm -rf /var/lib/apt/lists/*

# Copy PHP installation from builder
COPY --from=php-builder /usr/local /usr/local

# Make sure libphp.so is findable
RUN ldconfig

# Verify PHP works
RUN php -v && php-config --php-sapis

# Install Rust
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.85.0
ENV PATH="/root/.cargo/bin:${PATH}"

# Copy workspace
WORKDIR /src
COPY . .

# Build the embed crate
RUN cargo build -p folk-runtime-embed 2>&1

# Run tests (single-threaded — PHP embed is not re-entrant)
CMD ["cargo", "test", "-p", "folk-runtime-embed", "--", "--test-threads=1", "--nocapture"]
