#!/usr/bin/env bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
KISSAT="$SCRIPT_DIR/kissat"

set -euo pipefail

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 formula.cnf solver_output.txt"
  exit 1
fi

CNF="$1"
OUT="$2"

TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT

# Extract model from v-lines and convert to unit clauses
grep '^v' "$OUT" \
  | sed 's/^v //' \
  | tr ' ' '\n' \
  | grep -v '^0$' \
  | sed 's/$/ 0/' > "$TMP"

# Combine original CNF with unit clauses
COMBINED=$(mktemp)
trap 'rm -f "$TMP" "$COMBINED"' EXIT

# Append the units to the end of the CNF
# We use an intervening `echo` in case the CNF doesn't end with a newline
cat "$CNF" > "$COMBINED"
echo "" >> "$COMBINED"
cat "$TMP" >> "$COMBINED"

# Run CaDiCaL
RESULT=$($KISSAT --relaxed "$COMBINED" | grep '^s ' || true)

echo "$RESULT"

if echo "$RESULT" | grep -q "UNSAT"; then
  echo "Model is INVALID (does not satisfy formula)"
  exit 2
elif echo "$RESULT" | grep -q "SAT"; then
  echo "Model is VALID"
  exit 0
else
  echo "Unexpected solver result"
  exit 3
fi
