# syntax=docker/dockerfile:1.7

ARG PYTHON_VERSION=3.11-slim
ARG APT_CACHE_URL=http://192.168.88.14:3142

FROM python:${PYTHON_VERSION} AS builder
ARG APT_CACHE_URL

ENV \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PIP_NO_CACHE_DIR=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

COPY requirements.txt ./requirements.txt

RUN --mount=type=cache,target=/root/.cache/pip /bin/bash <<'EOF'
set -e

python3 <<'PY'
import os, socket, urllib.parse

url = os.environ.get('APT_CACHE_URL', '').strip()
if url:
    parsed = urllib.parse.urlparse(url)
    host = parsed.hostname
    port = parsed.port or (80 if parsed.scheme == 'http' else 443)
    if host:
        sock = socket.socket()
        sock.settimeout(1)
        try:
            sock.connect((host, port))
        except OSError:
            pass
        else:
            with open('/etc/apt/apt.conf.d/01proxy', 'w', encoding='utf-8') as fh:
                fh.write(f"Acquire::http::Proxy \"{url}\";\n")
                fh.write(f"Acquire::https::Proxy \"{url}\";\n")
        finally:
            sock.close()
PY
APT_PROXY_CONFIG=/etc/apt/apt.conf.d/01proxy

apt_update_with_fallback() {
    if ! apt-get update; then
        rm -f "$APT_PROXY_CONFIG"
        apt-get update
    fi
}

apt_install_with_fallback() {
    if ! apt-get install -y --no-install-recommends "$@"; then
        rm -f "$APT_PROXY_CONFIG"
        apt-get update
        apt-get install -y --no-install-recommends "$@"
    fi
}

apt_update_with_fallback
apt_install_with_fallback build-essential gcc libpq-dev
pip install --upgrade pip
pip wheel --no-deps --wheel-dir /wheels -r requirements.txt
apt-get purge -y --auto-remove build-essential gcc
rm -rf /var/lib/apt/lists/*
EOF

FROM python:${PYTHON_VERSION} AS runtime
ARG APT_CACHE_URL

ENV \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PIP_NO_CACHE_DIR=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PATH="/home/appuser/.local/bin:${PATH}"

WORKDIR /app

RUN groupadd --system app && useradd --system --create-home --gid app appuser

RUN /bin/bash <<'EOF'
set -e

python3 <<'PY'
import os, socket, urllib.parse

url = os.environ.get('APT_CACHE_URL', '').strip()
if url:
    parsed = urllib.parse.urlparse(url)
    host = parsed.hostname
    port = parsed.port or (80 if parsed.scheme == 'http' else 443)
    if host:
        sock = socket.socket()
        sock.settimeout(1)
        try:
            sock.connect((host, port))
        except OSError:
            pass
        else:
            with open('/etc/apt/apt.conf.d/01proxy', 'w', encoding='utf-8') as fh:
                fh.write(f"Acquire::http::Proxy \"{url}\";\n")
                fh.write(f"Acquire::https::Proxy \"{url}\";\n")
        finally:
            sock.close()
PY
APT_PROXY_CONFIG=/etc/apt/apt.conf.d/01proxy

apt_update_with_fallback() {
    if ! apt-get update; then
        rm -f "$APT_PROXY_CONFIG"
        apt-get update
    fi
}

apt_install_with_fallback() {
    if ! apt-get install -y --no-install-recommends "$@"; then
        rm -f "$APT_PROXY_CONFIG"
        apt-get update
        apt-get install -y --no-install-recommends "$@"
    fi
}

apt_update_with_fallback
apt_install_with_fallback libpq5
rm -rf /var/lib/apt/lists/*
EOF

COPY --from=builder /wheels /wheels
COPY --from=builder /app/requirements.txt /tmp/requirements.txt

RUN pip install --upgrade pip \
    && pip install --no-cache-dir --find-links=/wheels -r /tmp/requirements.txt \
    && rm -rf /wheels /tmp/requirements.txt

COPY . /app

RUN chown -R appuser:app /app

USER appuser

EXPOSE 8003

ENTRYPOINT ["uvicorn"]

CMD ["main:app", "--host", "0.0.0.0", "--port", "8003", "--workers", "4"]
