#!/usr/bin/env bash
# File: packages/common/python-runtime.sh
# Purpose: Reuse compatible Python or provision a verified, private POSIX runtime.
# Integration: macOS/Linux setup and installed launchers source this helper.
# Downloads are pinned Astral Python Build Standalone releases, never a system install.

drishx_runtime_log() {
    printf '%s\n' "$2" >&2
    if [[ "${DRISHX_DRY_RUN:-0}" != 1 ]]; then
        mkdir -p "$1/.cache"
        printf '%s %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$2" >> "$1/.cache/launcher.log"
    fi
}

drishx_probe_python() {
    local candidate="$1" root="$2" result version executable
    [[ -x "$candidate" ]] || return 1
    if result=$("$candidate" -I -c 'import sys,struct; print(".".join(map(str,sys.version_info[:3])),flush=True); assert (3,10) <= sys.version_info[:2] < (3,14) and struct.calcsize("P")==8; import venv,ensurepip,ssl,sqlite3; print(sys.executable)' 2>/dev/null); then
        version="${result%%$'\n'*}"; executable="${result#*$'\n'}"
        [[ -x "$executable" ]] || return 1
        drishx_runtime_log "$root" "Using compatible Python $version: $executable. Dependencies stay in the DrishX environment."
        printf '%s\n' "$executable"; return 0
    fi
    version="${result%%$'\n'*}"
    drishx_runtime_log "$root" "Detected Python ${version:-unavailable} at $candidate; it is incompatible or lacks required runtime modules. Checking other runtimes; this installation stays unchanged."
    return 1
}

drishx_find_python() {
    local root="$1" candidate name location
    for candidate in "$root/.venv/bin/python" "$root/.python/bin/python3" "$root/.installer-ui/bin/python"; do
        if drishx_probe_python "$candidate" "$root"; then return 0; fi
    done
    for name in python3 python3.13 python3.12 python3.11 python3.10; do
        candidate=$(command -v "$name" 2>/dev/null || true)
        # Apple's developer-tools shim can prompt for Xcode installation on a
        # clean Mac. Use app/Homebrew Python or our private runtime instead.
        if [[ "$(uname -s)" == Darwin && "$candidate" == /usr/bin/python3 ]]; then candidate=''; fi
        if [[ -n "$candidate" ]] && drishx_probe_python "$candidate" "$root"; then return 0; fi
        if [[ "$(uname -s)" == Darwin ]]; then
            for location in /opt/homebrew/bin /usr/local/bin; do
                if drishx_probe_python "$location/$name" "$root"; then return 0; fi
            done
        fi
    done
    return 1
}

drishx_runtime_asset() {
    local platform="$(uname -s)" machine="$(uname -m)" triple hash
    case "$platform-$machine" in
        Darwin-arm64|Darwin-aarch64) triple=aarch64-apple-darwin; hash=11785155d0f70e634178219c20925d8f20be00a3da4684fc4f5019dd15602ef7 ;;
        Darwin-x86_64) triple=x86_64-apple-darwin; hash=bd085c51e960f00ee33b630e2b13ac90fe90cdc3da25a0f0bc0719b1294920bf ;;
        Linux-arm64|Linux-aarch64) triple=aarch64-unknown-linux-gnu; hash=52c6993abd6ac687cceb787ecee83b166271bc06ad80ac9cac82c5d28d3c00bc ;;
        Linux-x86_64) triple=x86_64-unknown-linux-gnu; hash=24801ea31c7d406d559a17e2226325c723d50c56900b9c0da7b62adaae2affc9 ;;
        *) printf 'Unsupported private Python platform: %s / %s\n' "$platform" "$machine" >&2; return 1 ;;
    esac
    printf '%s %s\n' "cpython-3.13.16+20261009-$triple-install_only_stripped.tar.gz" "$hash"
}

drishx_sha256() {
    if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d ' ' -f 1
    else shasum -a 256 "$1" | cut -d ' ' -f 1; fi
}

drishx_download_python() (
    set -euo pipefail
    local root="$1" asset filename hash cache archive stage='' lock owned=0 count=0 backup='' python
    asset=$(drishx_runtime_asset) || return 1
    filename="${asset%% *}"; hash="${asset#* }"
    cache="$root/.cache"; archive="$cache/$filename"; lock="$cache/python-runtime.lock"
    mkdir -p "$cache" || return 1
    cleanup() { [[ -z "$stage" ]] || rm -rf "$stage"; [[ "$owned" != 1 ]] || rmdir "$lock"; }
    trap cleanup EXIT
    trap 'exit 130' INT
    trap 'exit 143' TERM
    until mkdir "$lock" 2>/dev/null; do
        if [[ "$count" -ge 120 ]]; then printf 'Another runtime setup is still running. Try again after it finishes.\n' >&2; return 1; fi
        sleep 1; count=$((count+1))
    done
    owned=1
    if drishx_probe_python "$root/.python/bin/python3" "$root"; then return 0; fi
    drishx_runtime_log "$root" 'No compatible Python found. Preparing DrishX private runtime automatically; system Python and PATH stay unchanged.'
    if [[ ! -f "$archive" ]] || [[ "$(drishx_sha256 "$archive")" != "$hash" ]]; then
        if ! curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 --retry 3 --connect-timeout 30 \
            "https://github.com/astral-sh/python-build-standalone/releases/download/20261009/${filename//+/%2B}" -o "$archive.partial"; then
            rm -f "$archive.partial"; printf 'Private Python download failed. Check the connection and retry setup.\n' >&2; return 1
        fi
        if [[ "$(drishx_sha256 "$archive.partial")" != "$hash" ]]; then
            rm -f "$archive.partial"; printf 'Private Python checksum mismatch; nothing was installed.\n' >&2; return 1
        fi
        mv "$archive.partial" "$archive" || return 1
    fi
    stage=$(mktemp -d "$cache/python-runtime.XXXXXX") || return 1
    tar -xzf "$archive" -C "$stage" || return 1
    if ! drishx_probe_python "$stage/python/bin/python3" "$root" >/dev/null; then
        printf 'Downloaded private Python could not run on this system. See runtime details in %s/launcher.log.\n' "$cache" >&2; return 1
    fi
    if [[ -e "$root/.python" || -L "$root/.python" ]]; then
        backup="$cache/previous-python-$(date +%s)-$$"
        mv "$root/.python" "$backup" || return 1
    fi
    if ! mv "$stage/python" "$root/.python"; then
        [[ -z "$backup" ]] || mv "$backup" "$root/.python"
        return 1
    fi
    if python=$(drishx_probe_python "$root/.python/bin/python3" "$root"); then
        printf '%s\n' "$python"
    else
        mv "$root/.python" "$stage/failed-python" || return 1
        [[ -z "$backup" ]] || mv "$backup" "$root/.python"
        printf 'Private Python could not start after installation; previous runtime restored.\n' >&2
        return 1
    fi
)

drishx_resolve_python() {
    local root="$1"
    if drishx_find_python "$root"; then return 0; fi
    if [[ "${DRISHX_DRY_RUN:-0}" == 1 ]]; then
        printf 'Dry run: setup would download and verify a private Python runtime for %s.\n' "$root" >&2; return 2
    fi
    drishx_download_python "$root"
}

drishx_target_dir() {
    local target="$1"; shift
    while [[ "$#" -gt 0 ]]; do
        case "$1" in
            --target-dir) [[ "$#" -ge 2 ]] || return 1; target="$2"; shift ;;
            --target-dir=*) target="${1#*=}" ;;
        esac
        shift
    done
    printf '%s\n' "$target"
}

drishx_run_installer() {
    local target="$1" installer="$2" python status argument; shift 2
    DRISHX_DRY_RUN=0
    for argument in "$@"; do [[ "$argument" != --dry-run ]] || DRISHX_DRY_RUN=1; done
    if python=$(drishx_resolve_python "$target"); then
        # Other apps may set Python variables globally. Clear them only in the
        # owned child so environment creation and desktop launch stay isolated.
        env -u PYTHONHOME -u PYTHONPATH "$python" "$installer" --target-dir "$target" "$@"
    else
        status=$?
        [[ "$status" == 2 && "$DRISHX_DRY_RUN" == 1 ]] && return 0
        return "$status"
    fi
}
