#!/bin/bash
# weave_cleanup.sh — Reset this weave to a clean state
# Deletes collected data, clears logs, and strips notebook outputs.
set -e

WEAVE_DIR="$(cd "$(dirname "$0")" && pwd)"
DATA_DIR="${WEAVE_DIR}/data"
NOTEBOOKS_DIR="${WEAVE_DIR}/notebooks"

echo "=== Weave Cleanup ==="
echo "  Weave dir: ${WEAVE_DIR}"
echo

# --- 1. Delete collected data results ---
echo "Cleaning data directory..."
find "${DATA_DIR}" -type f ! -name '.gitkeep' -delete 2>/dev/null || true
echo "  Removed data files (kept .gitkeep)"

# --- 2. Clear logs ---
echo "Clearing logs..."
: > "${WEAVE_DIR}/weave.log"
echo "  Cleared weave.log"

# --- 3. Reset Jupyter notebooks (strip outputs) ---
echo "Resetting notebooks..."
if command -v jupyter &>/dev/null; then
    for nb in "${NOTEBOOKS_DIR}"/*.ipynb; do
        [ -f "$nb" ] || continue
        jupyter nbconvert --ClearOutputPreprocessor.enabled=True \
            --to notebook --inplace "$nb" 2>/dev/null
        echo "  Cleared outputs: $(basename "$nb")"
    done
elif command -v python3 &>/dev/null; then
    # Fallback: use Python directly to strip outputs
    python3 -c "
import json, glob, sys

for path in glob.glob('${NOTEBOOKS_DIR}/*.ipynb'):
    with open(path) as f:
        nb = json.load(f)
    for cell in nb.get('cells', []):
        cell['outputs'] = [] if cell.get('cell_type') == 'code' else cell.get('outputs', [])
        if cell.get('cell_type') == 'code':
            cell['outputs'] = []
            cell['execution_count'] = None
    with open(path, 'w') as f:
        json.dump(nb, f, indent=1)
        f.write('\n')
    print(f'  Cleared outputs: {path.split(\"/\")[-1]}')
"
else
    echo "  WARNING: Neither jupyter nor python3 found — cannot clear notebooks"
fi

# Remove notebook checkpoints
rm -rf "${NOTEBOOKS_DIR}/.ipynb_checkpoints" 2>/dev/null || true
echo "  Removed .ipynb_checkpoints"

echo
echo "Done. Weave is clean and ready for a fresh run."
