#!/usr/bin/env bash
# Shared Pi Python / apt policy for DyzineFrame install.sh + update.sh.
# Sourced, not executed.
#
# Field is Raspberry Pi OS Bookworm, system python3 == 3.11.
# apt full-upgrade and pip --upgrade can roll to Trixie/3.13 or break pygame.

# shellcheck shell=bash

_df_policy_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

df_require_supported_python() {
  local py ver major minor
  py="${DF_PYTHON:-python3}"
  if ! command -v "${py}" >/dev/null 2>&1; then
    echo "FATAL: ${py} not found. DyzineFrame needs Bookworm python3 (3.11)." >&2
    return 1
  fi
  ver="$("${py}" -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
  major="${ver%%.*}"
  minor="${ver#*.}"
  echo "python: ${py} ${ver} ($("${py}" -c 'import sys; print(sys.executable)'))"
  if [[ "${major}" != "3" ]] || [[ "${minor}" -lt 9 ]] || [[ "${minor}" -gt 11 ]]; then
    echo "FATAL: DyzineFrame supports Python 3.9–3.11 only (Bookworm = 3.11). Got ${ver}." >&2
    echo "  Do not apt full-upgrade toward Trixie (Python 3.13) or retarget python3." >&2
    echo "  Leave this OS as Bookworm. Code pulls: ~/EtherGold/sync/pull_all_from_dropbox.sh" >&2
    return 1
  fi
}

# Install missing OS deps only. Never apt full-upgrade / dist-upgrade.
df_apt_install_df_deps() {
  echo "apt: install missing deps only (no full-upgrade)"
  sudo apt-get update -y
  sudo apt-get install -y --no-install-recommends \
    htop systemd-timesyncd ffmpeg python3 python3-pip python3-dev python3-venv \
    portaudio19-dev
}

# Ensure listed modules exist. Default does NOT roll versions (--upgrade is opt-in).
df_pip_ensure_df_modules() {
  local py="${DF_PYTHON:-python3}"
  local pkgs=(pyvidplayer2 bottle extended-configparser qrcode pyserial natsort pygame)
  local extra=()
  if [[ "${FORCE_PIP_UPGRADE:-0}" == "1" ]]; then
    echo "pip: FORCE_PIP_UPGRADE=1 — upgrading ${pkgs[*]}"
    extra+=(--upgrade)
  else
    echo "pip: ensure present (no --upgrade; set FORCE_PIP_UPGRADE=1 to roll)"
  fi
  if [[ ${#extra[@]} -gt 0 ]]; then
    "${py}" -m pip install --break-system-packages "${extra[@]}" "${pkgs[@]}"
  else
    "${py}" -m pip install --break-system-packages "${pkgs[@]}"
  fi
}
