#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")"

echo "🌐 Running nickel-roundtrip with Web backend..."
echo ""

# Check if config.ncl exists
if [ ! -f "config.ncl" ]; then
    echo "❌ config.ncl not found! Run ./01-generate-initial-config.sh first"
    exit 1
fi

# Backup current config
cp config.ncl "config.ncl.backup.$(date +%Y%m%d_%H%M%S)"

echo "Starting web server on http://localhost:8080"
echo "Your browser should open automatically..."
echo ""
echo "Features:"
echo "  ✓ All fields pre-populated with current values"
echo "  ✓ Real-time validation"
echo "  ✓ HTML diff viewer on submit"
echo "  ✓ Download button for config.ncl"
echo "  ✓ Auto-close after 30 seconds"
echo ""
echo "Press Ctrl+C after form is submitted to exit"
echo ""

# Open browser (macOS)
sleep 2 && open "http://localhost:8080" &

# Run roundtrip with Web backend
cargo run -p typedialog-web --release -- nickel-roundtrip \
    --input config.ncl \
    --form ci-form.ncl \
    --output config.ncl \
    --ncl-template config.ncl.j2 \
    --verbose

echo ""
echo "✅ Roundtrip completed!"
echo ""
echo "Review changes:"
echo "  cat config.ncl"
echo ""
echo "Run again:"
echo "  ./04-roundtrip-web.sh"
