FROM mcr.microsoft.com/playwright/python:v1.52.0-jammy

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

ARG PIP_INDEX_URL=https://mirrors.cloud.tencent.com/pypi/simple
ARG PIP_TRUSTED_HOST=mirrors.cloud.tencent.com

COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --retries 5 --timeout 120 \
    -i "${PIP_INDEX_URL}" --trusted-host "${PIP_TRUSTED_HOST}" \
    -r /app/requirements.txt

COPY app /app/app

EXPOSE 8317

# Container-level health signal. Docker Compose / orchestrators rely on this
# to stop sending traffic when the pool is wedged, restart unhealthy replicas,
# and drive rolling deploys. /healthz returns ok=true only when at least one
# Lingma instance is in state=ready, so it catches the "stuck on login" case
# that a raw TCP probe would miss.
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
    CMD python -c "import os,json,urllib.request,sys; \
port=os.environ.get('PORT','8317'); \
r=urllib.request.urlopen(f'http://127.0.0.1:{port}/healthz', timeout=3); \
sys.exit(0 if json.load(r).get('ok') else 1)" || exit 1

CMD ["sh", "-c", "python /app/app/bootstrap_lingma.py && uvicorn app.main:app --host ${HOST:-0.0.0.0} --port ${PORT:-8317}"]
