# --- Build stage: install dependencies ---
FROM python:3.14-slim AS builder

ENV PYTHONDONTWRITEBYTECODE=1

WORKDIR /app

COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv

# Install dependencies first (cached layer — only reruns when pyproject.toml/uv.lock change).
# OB_EXTRA selects the optional-dependency groups to install, one or several
# (separated by spaces or commas):
#   - flight-duckdb-only (default) — pyarrow + ob-flight-extension + ob-duckdb
#     only. Smallest image; used by the Cloud Run demo which only needs
#     the baked-in DuckDB seed.
#   - flight — pyarrow + ob-flight-extension + all 8 vendor drivers
#     (BigQuery, ClickHouse, Databricks, Dremio, DuckDB, MySQL, Postgres,
#     Snowflake). Required for integration tests that execute against a
#     non-DuckDB backend (e.g. the Dremio Stage-2 suite).
#   - hardcharger: the driver for DuckDB sources whose queries run on
#     Hardcharger workers, beside one of the above:
#     --build-arg OB_EXTRA="flight-duckdb-only hardcharger".
#
# Copy the workspace members (drivers/ and packages/) before the sync so uv
# can resolve the workspace graph. The flight* extras pull the osi-orionbelt
# member under packages/, so it must be present at this first sync.
ARG OB_EXTRA=flight-duckdb-only
COPY pyproject.toml uv.lock README.md LICENSE ./
COPY drivers/ drivers/
COPY packages/ packages/
RUN uv sync --no-dev --no-install-project --frozen \
    $(for extra in $(echo "${OB_EXTRA}" | tr ',' ' '); do printf -- '--extra %s ' "$extra"; done)

# Copy source and install the project itself (osi-orionbelt vendors its own
# schemas; schema/ here is for the main package's reference endpoints).
COPY src/ src/
COPY schema/ schema/
RUN uv sync --no-dev --no-editable --frozen \
    $(for extra in $(echo "${OB_EXTRA}" | tr ',' ' '); do printf -- '--extra %s ' "$extra"; done)

# The ADBC MySQL driver ob_mysql reads through (not on PyPI; pinned and
# checksummed), when the extra installs ob_mysql. Without it ob_mysql falls
# back to PyMySQL. /opt/adbc exists either way for the runtime COPY.
COPY scripts/install_adbc_mysql.py scripts/
RUN mkdir -p /opt/adbc \
    && if .venv/bin/python -c "import ob_mysql" 2>/dev/null; then \
        python scripts/install_adbc_mysql.py /opt/adbc; \
    fi

# --- Runtime stage: minimal image ---
FROM python:3.14-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

# Install IANA tzdata so Python's zoneinfo can resolve names like
# Europe/Berlin. python:3.14-slim has no /usr/share/zoneinfo, and without
# it ZoneInfo("Europe/Berlin") raises ZoneInfoNotFoundError — the timezone
# resolver then silently falls back to UTC. Belt-and-suspenders alongside
# the tzdata Python dep.
RUN apt-get update \
    && apt-get install -y --no-install-recommends tzdata \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd -r app && useradd -r -g app -d /app -s /sbin/nologin app

# Copy installed virtualenv from builder
COPY --from=builder --chown=app:app /app/.venv /app/.venv
COPY --from=builder /opt/adbc /opt/adbc
ENV PATH="/app/.venv/bin:$PATH" \
    ADBC_DRIVER_PATH=/opt/adbc/drivers

# Copy schema (needed at runtime for validation)
COPY --from=builder --chown=app:app /app/schema schema/

# The OSI <-> OBML converter is installed into the venv as the osi-orionbelt
# package (with its schemas bundled), so no separate copy is needed here.

# Bake the matching OBML model into the image, plus the public-demo dataset
# when it is present in the build context, so the Cloud Run service can
# answer /v1/query/execute without external infra. The .duckdb file is
# gitignored and pre-generated by scripts/build_demo_duckdb.py before the
# docker build (see deploy-gcloud.sh). The trailing glob on the .duckdb makes
# that source optional: the public Docker Hub build has no seed and ships
# without it, while the .yaml (always present) keeps the COPY source set
# non-empty so the build never fails.
COPY --chown=app:app examples/orionbelt_1_commerce.yaml examples/orionbelt_1_commerce.duckdb* /app/data/

# Where federated queries spill large legs, when FEDERATION_SPILL_DIR=/app/spill
# (else into /tmp, the container's writable layer). Owned by the app user, so a
# named volume mounted here starts out writable: Docker copies the directory's
# owner into a new volume.
#   docker run -v obsl-spill:/app/spill -e FEDERATION_SPILL_DIR=/app/spill ...
RUN mkdir -p /app/spill && chown app:app /app/spill

# DuckDB keeps its extensions in the user's home, /app/.duckdb. A DuckDB data
# source reading object storage or an Iceberg catalog loads httpfs, iceberg and
# avro on first use; owned by the app user, the directory lets DuckDB download
# them then. DUCKDB_EXTENSIONS installs them into the image instead, for a host
# that cannot reach extensions.duckdb.org (about 105 MB for those three):
#   docker build --build-arg DUCKDB_EXTENSIONS="httpfs iceberg avro" ...
ARG DUCKDB_EXTENSIONS=""
RUN mkdir -p /app/.duckdb && chown app:app /app/.duckdb

USER app

RUN if [ -n "$DUCKDB_EXTENSIONS" ]; then \
        python -c "import sys, duckdb; con = duckdb.connect(); [con.install_extension(name) for name in sys.argv[1:]]" $DUCKDB_EXTENSIONS; \
    fi

# Cloud Run injects PORT (default 8080)
ENV PORT=8080 \
    API_SERVER_HOST=0.0.0.0 \
    LOG_LEVEL=INFO \
    LOG_FORMAT=json \
    DISABLE_SESSION_LIST=true \
    EXPOSE_API_DOCS=true \
    EXPOSE_OPENAPI_SCHEMA=true \
    DB_VENDOR=duckdb \
    DUCKDB_DATABASE=/app/data/orionbelt_1_commerce.duckdb \
    MODEL_DIR=/app/data \
    MODEL_FILES=orionbelt_1_commerce.yaml

EXPOSE ${PORT}
# Arrow Flight SQL, when FLIGHT_ENABLED=true. Documentation only - the image
# advertised just the HTTP port while being able to serve this one too.
EXPOSE 8815

# Health check for local Docker / Compose (Cloud Run uses its own probes)
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen(f'http://localhost:{__import__(\"os\").environ[\"PORT\"]}/health')"

# Single worker — Cloud Run scales by adding container instances, not workers
CMD ["sh", "-c", "uvicorn orionbelt.api.app:create_app --factory --host 0.0.0.0 --port $PORT --log-level info --proxy-headers --forwarded-allow-ips='*' --no-access-log"]
