#!/usr/bin/env bash
# ci-test.sh: Local CI sanity check without pushing
# Run from repository root

set -euo pipefail

REPO_ROOT="$(pwd)"
CLI_DIR="${REPO_ROOT}/cli"
DIST_DIR="${REPO_ROOT}/dist"
CONFIG_DIR="${REPO_ROOT}/configs"

# Cleanup on exit
cleanup() {
    local exit_code=$?
    echo ""
    echo "[cleanup] Removing temporary build artifacts..."
    rm -rf "${CLI_DIR}/zig-out" "${CLI_DIR}/.zig-cache"
    if [[ "${exit_code}" -eq 0 ]]; then
        echo "[cleanup] CI passed. Keeping dist/ for inspection."
    else
        echo "[cleanup] CI failed. Cleaning dist/ as well."
        rm -rf "${DIST_DIR}"
    fi
}
trap cleanup EXIT

echo "=== Local CI sanity check ==="
echo "Repo root: ${REPO_ROOT}"
echo ""

# 1. CLI build (native, mimicking release.yml)
echo "[1] Building CLI (native)..."
cd "${CLI_DIR}"
rm -rf zig-out .zig-cache
zig build -Doptimize=ReleaseSmall
ls -lh zig-out/bin/ml

# Optional: cross-target test if your Zig supports it
if command -v zig >/dev/null 2>&1; then
    echo ""
    echo "[1b] Testing cross-target (linux-x86_64) if supported..."
    if zig targets | grep -q x86_64-linux-gnu; then
        rm -rf zig-out .zig-cache
        zig build -Doptimize=ReleaseSmall -Dtarget=x86_64-linux-gnu
        ls -lh zig-out/bin/ml
    else
        echo "Cross-target x86_64-linux-gnu not available; skipping."
    fi
fi

# 2. Package CLI like CI does
echo ""
echo "[2] Packaging CLI artifact..."
mkdir -p "${DIST_DIR}"
cp "${CLI_DIR}/zig-out/bin/ml" "${DIST_DIR}/ml-test"
cd "${DIST_DIR}"
tar -czf ml-test.tar.gz ml-test
sha256sum ml-test.tar.gz > ml-test.tar.gz.sha256
ls -lh ml-test.tar.gz*

# 3. Go backends (if applicable)
echo ""
echo "[3] Building Go backends (cross-platform)..."
cd "${REPO_ROOT}"
if [ -f Makefile ] && grep -q 'cross-platform' Makefile; then
    make cross-platform
    ls -lh dist/
else
    echo "No 'cross-platform' target found in Makefile; skipping Go backends."
fi

echo ""
echo "=== Local CI check complete ==="
echo "If all steps succeeded, your CI changes are likely safe to push."
