#!/usr/bin/env bash
#
# common.sh — shared helpers for the scripts/ build scripts.
#
# Source this from the other scripts/ build scripts (after setting SCRIPT_DIR):
#
#   SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
#   VC_SCRIPT_NAME="build-foo"   # optional, for nicer log prefixes
#   source "$SCRIPT_DIR/common.sh"
#
# What it provides:
#   - repo-root + dist-dir resolution (default <repo>/dist; override with
#     --dist <path> via vc_set_dist, or the VOICECAT_DIST_DIR env var).
#   - VCPKG_ROOT detection (env var first, then an existing CMake cache).
#   - host-platform guards (vc_require_macos / vc_require_windows / vc_host_os).
#   - uniform [tag] logging + a portable file-size helper.
#   - vc_dist_subdir <name>: create (clean) and echo $DIST/<name>.
#   - vc_print_help <file>: print a script's leading "# " comment block as the
#     --help text (so each script's header comment IS its help).
#
# Not meant to be run directly.

# This file lives in scripts/, so the repo root is one level up.
VC_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VC_REPO_ROOT="$(cd "$VC_SCRIPT_DIR/.." && pwd)"

# Display name for log lines (defaults to the caller's filename).
VC_SCRIPT_NAME="${VC_SCRIPT_NAME:-$(basename "${BASH_SOURCE[1]:-$0}")}"

# Dist dir — env override resolved here; --dist updates it via vc_set_dist.
VC_DIST_DIR="${VOICECAT_DIST_DIR:-$VC_REPO_ROOT/dist}"

# ── Logging ─────────────────────────────────────────────────────────────────────
vc_log()  { printf '\033[1;34m[%s]\033[0m %s\n' "$VC_SCRIPT_NAME" "$*"; }
vc_step() { printf '\033[1;36m[%s] === %s ===\033[0m\n' "$VC_SCRIPT_NAME" "$*"; }
vc_ok()   { printf '\033[1;32m[%s]\033[0m %s\n' "$VC_SCRIPT_NAME" "$*"; }
vc_err()  { printf '\033[1;31m[%s] error:\033[0m %s\n' "$VC_SCRIPT_NAME" "$*" >&2; }
vc_die()  { vc_err "$*"; exit 1; }

# Portable file size (macOS `stat -f%z` vs coreutils `stat -c%s`).
vc_file_size() {
    stat -f%z "$1" 2>/dev/null || stat -c%s "$1" 2>/dev/null
}

# ── Dist dir ────────────────────────────────────────────────────────────────────
# Set/override the dist directory (called when a script sees --dist <path>).
vc_set_dist() {
    VC_DIST_DIR="$1"
    mkdir -p "$VC_DIST_DIR"
}

# Create (clean) and echo a subdirectory under dist/.
vc_dist_subdir() {
    local path="$VC_DIST_DIR/$1"
    rm -rf "$path"
    mkdir -p "$path"
    echo "$path"
}

# ── Platform helpers ────────────────────────────────────────────────────────────
vc_host_os() {
    case "$(uname -s)" in
        Darwin)             echo macos ;;
        MINGW*|MSYS*|CYGWIN*) echo windows ;;
        Linux)              echo linux ;;
        *)                  echo unknown ;;
    esac
}

vc_require_macos() {
    [[ "$(uname -s)" == "Darwin" ]] \
        || vc_die "this script must be run on macOS (uname -s = $(uname -s))."
}

vc_require_windows() {
    local s; s="$(uname -s)"
    [[ "$s" == MINGW* || "$s" == MSYS* || "$s" == CYGWIN* ]] \
        || vc_die "this script must be run on Windows (MSYS2/MinGW). uname -s = $s."
}

# ── VCPKG_ROOT ──────────────────────────────────────────────────────────────────
# Honor the env var, else try to read it from an existing CMake cache
# (Z_VCPKG_ROOT_DIR) so a developer who already configured a preset doesn't need
# VCPKG_ROOT in their shell env. $1 = the preset whose cache to probe as a
# fallback (e.g. "dev" or "apple-dev").
vc_resolve_vcpkg_root() {
    local fallback_preset="${1:-dev}"
    if [[ -z "${VCPKG_ROOT:-}" ]]; then
        local cache="$VC_REPO_ROOT/build/$fallback_preset/CMakeCache.txt"
        if [[ -f "$cache" ]]; then
            local detected
            detected="$(grep -m1 '^Z_VCPKG_ROOT_DIR:INTERNAL=' "$cache" | cut -d= -f2- || true)"
            if [[ -n "$detected" && -d "$detected" ]]; then
                export VCPKG_ROOT="$detected"
            fi
        fi
    fi
    if [[ -z "${VCPKG_ROOT:-}" || ! -d "$VCPKG_ROOT" ]]; then
        vc_die "VCPKG_ROOT is not set or does not exist.
       bootstrap vcpkg (https://vcpkg.io) then:
         export VCPKG_ROOT=/path/to/vcpkg"
    fi
    vc_log "VCPKG_ROOT=$VCPKG_ROOT"
}

# ── Help ────────────────────────────────────────────────────────────────────────
# Print a script's leading "# " comment block (skipping the shebang) as help.
vc_print_help() {
    awk 'NR==1{next} /^#[[:space:]]?/{sub(/^#[[:space:]]?/,""); print; next} {exit}' "$1"
}
