# The solution architecture agent: the Execution engine and this Workflow.
#
# The engine comes from a named build context, so no file is copied by hand:
#
#   podman build --build-context engine=../orchestration_engine -t solution-architecture .
#
# The agent itself is not installed: its role files, Skills and provider bundle are
# found beside its code (ROOT in app/main.py), so it runs from /app.

FROM python:3.12-slim AS builder

RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates unzip \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /engine
COPY --from=engine pyproject.toml ./
COPY --from=engine execution_engine/ ./execution_engine/
COPY --from=engine orchestration/ ./orchestration/
RUN pip install --no-cache-dir --prefix=/install .

# Terraform, for the local fmt, validate and plan tools (never apply).
ARG TERRAFORM_VERSION=1.14.3
RUN curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip" \
    && curl -fsSLO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_SHA256SUMS" \
    && grep "linux_amd64.zip" "terraform_${TERRAFORM_VERSION}_SHA256SUMS" | sha256sum -c - \
    && unzip "terraform_${TERRAFORM_VERSION}_linux_amd64.zip" -d /usr/local/bin \
    && rm "terraform_${TERRAFORM_VERSION}_linux_amd64.zip" "terraform_${TERRAFORM_VERSION}_SHA256SUMS"


FROM python:3.12-slim

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONPATH=/app \
    A2A_HOST=0.0.0.0 \
    A2A_PORT=8080 \
    CHECKPOINTER=sqlite \
    CHECKPOINT_DB_PATH=/data/checkpoints.db \
    SQLITE_FALLBACK_DB=/data/agent_local.db \
    TF_PLUGIN_CACHE_DIR=/data/terraform-plugins \
    ENV_FILE_EXPORT=false

WORKDIR /app

RUN groupadd -g 10001 appgroup && \
    useradd -u 10001 -g appgroup -s /bin/sh -m appuser

COPY --from=builder /install /usr/local
COPY --from=builder /usr/local/bin/terraform /usr/local/bin/terraform

COPY app/ ./app/
COPY agents/ ./agents/
COPY providers/ ./providers/
COPY skills/ ./skills/

RUN mkdir -p deliverables lessons /data && chown -R appuser:appgroup /app /data

USER appuser
VOLUME ["/data"]
EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
  CMD python -c "import os, urllib.request; urllib.request.urlopen(f'http://localhost:{os.environ[\"A2A_PORT\"]}/health')" || exit 1

CMD ["python", "-m", "app.main"]
