#!/usr/bin/env bash
# Create a clean MoonBit consumer, install quiescent from mooncakes, and run
# one SAT and one UNSAT check. Intended to finish in under ten minutes.
#
# Environment:
#   QUIESCENT_VERSION       quiescent version to install (default: 0.9.0-rc1;
#                           use 0.5.0 before the prerelease is published)
#   QUIESCENT_CONSUMER_DIR  fixed base directory; each run creates a fresh
#                           project-<timestamp>-<pid> under it and keeps the
#                           base plus all previous projects
#   QUIESCENT_MOON_HOME     if non-empty, exported as MOON_HOME (MoonBit
#                           registry/cache root)
#   TMPDIR                  parent for the default mktemp base directory
#   QUIESCENT_KEEP_CONSUMER if 1, keep the default mktemp base on success
set -euo pipefail

trap 'status=$?; echo "quickstart failed (exit $status) at: $BASH_COMMAND" >&2; exit $status' ERR

VERSION="${QUIESCENT_VERSION:-0.9.0-rc1}"
if [[ -n "${QUIESCENT_MOON_HOME:-}" ]]; then
  export MOON_HOME="$QUIESCENT_MOON_HOME"
fi

if [[ -n "${QUIESCENT_CONSUMER_DIR:-}" ]]; then
  BASE="$QUIESCENT_CONSUMER_DIR"
  CREATED_TEMP=0
else
  BASE="$(mktemp -d "${TMPDIR:-/tmp}/quiescent-consumer.XXXXXX")"
  CREATED_TEMP=1
fi
RUN_ID="$(date +%s)-$$"
WORKDIR="$BASE/project-$RUN_ID"
KEEP="${QUIESCENT_KEEP_CONSUMER:-0}"

cleanup() {
  if [[ "$KEEP" != "1" && "$CREATED_TEMP" == "1" ]]; then
    rm -rf "$BASE"
  fi
}
trap cleanup EXIT

mkdir -p "$BASE"

start=$SECONDS

# The MoonBit CLI is a native program; convert the POSIX temp path on Windows.
if command -v cygpath >/dev/null 2>&1; then
  WORKDIR_FOR_MOON="$(cygpath -w "$WORKDIR")"
else
  WORKDIR_FOR_MOON="$WORKDIR"
fi

moon new "$WORKDIR_FOR_MOON" --user local --name consumer >/dev/null
cd "$WORKDIR"
moon add "soehi/quiescent@${VERSION}" >/dev/null

cat > cmd/main/moon.pkg <<'EOF'
import {
  "soehi/quiescent/src",
}

pkgtype(kind: "executable")
EOF

cat > cmd/main/main.mbt <<'EOF'
///|
fn main raise {
  let sat = @src.parse_dimacs("p cnf 1 1\n1 0\n")
  let (r1, _s1) = @src.solve_without_proof(sat)
  match r1 {
    @src.Sat(model) => {
      if !@src.satisfies(sat, model) {
        raise Failure("model check failed")
      }
      println("SAT: \{model.length()} assignments")
    }
    @src.Unsat => raise Failure("expected SAT")
    @src.Unknown(reason) => raise Failure("unexpected UNKNOWN: \{reason}")
  }
  let unsat = @src.parse_dimacs("p cnf 1 2\n1 0\n-1 0\n")
  let (r2, s2) = @src.solve_without_proof(unsat)
  match r2 {
    @src.Sat(_) => raise Failure("expected UNSAT")
    @src.Unsat => println("UNSAT after \{s2.conflicts} conflicts")
    @src.Unknown(reason) => raise Failure("unexpected UNKNOWN: \{reason}")
  }
}
EOF

moon build --target native >/dev/null
set +e
output="$(moon run cmd/main --target native 2>&1)"
code=$?
set -e
printf '%s\n' "$output"
if (( code != 0 )); then
  exit "$code"
fi

expect_line() {
  local needle="$1"
  local label="$2"
  if ! grep -q -- "$needle" <<<"$output"; then
    printf '%s\n' "$output"
    echo "missing expected ${label} line: ${needle}" >&2
    exit 1
  fi
}
expect_line 'SAT: 1 assignments' 'SAT'
expect_line 'UNSAT after 1 conflicts' 'UNSAT'

elapsed=$((SECONDS - start))
echo "elapsed_s=$elapsed"
if (( elapsed >= 600 )); then
  echo "quickstart exceeded 10 minutes" >&2
  exit 1
fi
