## Stage 1: Resolve the package version from git tags.
## uv-dynamic-versioning needs .git to compute a PEP 440 version; we isolate
## that requirement here so .git never reaches the runtime image.
FROM python:3.12-slim AS version-resolver

COPY --from=ghcr.io/astral-sh/uv:0.8.17 /uv /uvx /bin/

RUN apt-get update \
    && apt-get install --no-install-recommends -y git \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY .git/ /app/.git/
COPY pyproject.toml /app/

# Resolve the PEP 440 version string (e.g. "0.75.2" or "0.75.1.post4.dev0+abc1234").
# Fail the build if resolution fails — falling back to 0.0.0 silently would
# reintroduce the exact production issue this stage exists to solve.
RUN uvx uv-dynamic-versioning > /resolved-version.txt

## Stage 2: Install dependencies and build the runtime image.
FROM python:3.12-slim

COPY --from=ghcr.io/astral-sh/uv:0.8.17 /uv /uvx /bin/

RUN apt-get update \
    && apt-get install --no-install-recommends -y git \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY pyproject.toml uv.lock README.md /app/
COPY src/ /app/src/
COPY airbyte-ops-webapp/ /app/airbyte-ops-webapp/

# Bring the resolved version from stage 1
COPY --from=version-resolver /resolved-version.txt /tmp/resolved-version.txt

WORKDIR /app/airbyte-ops-webapp

# UV_DYNAMIC_VERSIONING_BYPASS tells the build backend to use a static version
# instead of querying git (which is unavailable in this stage).
RUN UV_DYNAMIC_VERSIONING_BYPASS=$(cat /tmp/resolved-version.txt) uv sync --frozen --no-dev

ENV PATH="/app/airbyte-ops-webapp/.venv/bin:$PATH"
ENV PYTHONPATH="/app/airbyte-ops-webapp"
ENV TMPDIR="/app/airbyte-ops-webapp/.cache"
ENV PORT=8080

RUN mkdir -p "$TMPDIR" \
    && python -c "from fastmcp.cli.apps_dev import _EXT_APPS_VERSION, _MCP_SDK_VERSION, _fetch_app_bridge_bundle_sync; _fetch_app_bridge_bundle_sync(_EXT_APPS_VERSION, _MCP_SDK_VERSION)"

EXPOSE 8080

CMD ["python", "-m", "airbyte_ops_webapp.serve"]
