#!/bin/bash
# weave_cleanup.sh — teardown (the LoomAI cleanup script).
#
# LoomAI invokes this with the slice name as $1 (env SLICE_NAME wins). It deletes
# the FABRIC slice and clears local run artifacts. Use it when you are finished
# iterating in the notebook.
#
#   ./weave_cleanup.sh <slice-name>          # delete slice + clear results/
#   KEEP_RESULTS=true ./weave_cleanup.sh <slice-name>   # delete slice, keep results/
#   DELETE_SLICE=false ./weave_cleanup.sh <slice-name>  # clear results/ only, keep slice
set -uo pipefail

SLICE_NAME="${SLICE_NAME:-${1:-fl-grid}}"
SLICE_NAME=$(echo "$SLICE_NAME" | sed 's/[^a-zA-Z0-9-]/-/g; s/--*/-/g; s/^-//; s/-$//')
DELETE_SLICE="${DELETE_SLICE:-true}"
KEEP_RESULTS="${KEEP_RESULTS:-false}"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
RESULTS="$SCRIPT_DIR/results"

if [ "$DELETE_SLICE" = "true" ]; then
    echo "### PROGRESS: Deleting FABRIC slice '$SLICE_NAME'..."
    python3 "$SCRIPT_DIR/experiment.py" stop "$SLICE_NAME" 2>&1 || true
else
    echo "### PROGRESS: Keeping slice '$SLICE_NAME' (DELETE_SLICE=false)."
fi

if [ "$KEEP_RESULTS" != "true" ]; then
    echo "### PROGRESS: Clearing results/ (metrics, figures, slice_info)..."
    rm -f "$RESULTS"/metrics*.json "$RESULTS"/*.png "$RESULTS"/slice_info.json 2>/dev/null || true
fi

echo "### PROGRESS: Cleanup complete."
