# Build stage
FROM registry.access.redhat.com/ubi9/ubi-minimal AS builder

# Allow version to be set at build time
ARG INSIGHTS_MCP_VERSION

ARG CONTAINER_BRAND=insights
ENV CONTAINER_BRAND=${CONTAINER_BRAND}

# Set up a working directory
WORKDIR /app

RUN microdnf install -y --setopt=install_weak_deps=0 --setopt=tsflags=nodocs \
    python312 python3.12-pip && \
    microdnf clean all

# Copy the project configuration and required files
COPY pyproject.toml uv.lock README.md LICENSE ./
COPY src/ ./src/

# Temporarily switch to root for installation
USER root

# Install the package and its dependencies
# RUN pip install --no-cache-dir .
RUN pip3.12 install -U --no-cache-dir pip uv && \
    uv export --no-hashes > requirements.txt && \
    sed -i '/^-e ./d' requirements.txt && \
    pip3.12 install --no-cache-dir . -c requirements.txt && \
    pip3.12 install --no-cache-dir pip-licenses && \
    mkdir -p /licenses && \
    cp LICENSE /licenses/LICENSE && \
    pip-licenses --from=mixed \
      --format=plain-vertical --with-license-file --with-notice-file --no-license-path \
      --output-file=/licenses/third-party-notices.txt && \
    pip-licenses --from=mixed --format=rst \
      --output-file=/licenses/third-party-summary.rst && \
    pip3.12 uninstall -y pip-licenses uv pip

# Runtime stage
FROM registry.access.redhat.com/ubi9/ubi-minimal

# Inherit version from build stage
ARG INSIGHTS_MCP_VERSION
ENV INSIGHTS_MCP_VERSION=${INSIGHTS_MCP_VERSION}

ARG CONTAINER_BRAND=insights
ENV CONTAINER_BRAND=${CONTAINER_BRAND}

# MCP Registry ownership verification label
LABEL io.modelcontextprotocol.server.name="io.github.RedHatInsights/insights-mcp"

RUN microdnf install -y --setopt=install_weak_deps=0 --setopt=tsflags=nodocs \
    python312 shadow-utils && \
    useradd -r -s /bin/false -d /nonexistent mcpuser && \
    microdnf remove -y shadow-utils && \
    microdnf clean all

# Copy the installed packages from the builder stage
COPY --from=builder /usr/local/lib/python3.12/site-packages/ /usr/local/lib/python3.12/site-packages/
COPY --from=builder /usr/local/lib64/python3.12/site-packages/ /usr/local/lib64/python3.12/site-packages/
COPY --from=builder /usr/local/bin/ /usr/local/bin/
COPY --from=builder /licenses/ /licenses/

# Drop to non-root user for runtime
USER mcpuser

# Command to run the application
ENTRYPOINT ["python3.12", "-m", "insights_mcp"]
