#!/bin/bash

# Demo script: Wasot → SQLite → Wasot round-trip conversion
# Usage: ./scripts/demo <wasot-file>

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored output
print_step() {
    echo -e "${BLUE}📋 $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_info() {
    echo -e "${YELLOW}ℹ️  $1${NC}"
}

# Check if file argument is provided
if [ $# -eq 0 ]; then
    print_error "Usage: $0 <wasot-file>"
    echo "Example: $0 examples/demo.wasot"
    exit 1
fi

WASOT_FILE="$1"

# Check if file exists
if [ ! -f "$WASOT_FILE" ]; then
    print_error "File not found: $WASOT_FILE"
    exit 1
fi

# Generate temporary database file
TEMP_DB=$(mktemp /tmp/wasot_demo_XXXXXX.db)

# Cleanup function
cleanup() {
    rm -f "$TEMP_DB"
}
trap cleanup EXIT

echo -e "${BLUE}🚀 Wasot Round-Trip Conversion Demo${NC}"
echo "=================================="
echo

print_info "Input file: $WASOT_FILE"
print_info "Temporary database: $TEMP_DB"
echo

# Step 1: Show original content
print_step "Step 1: Original Wasot content"
echo "------------------------------"
cat "$WASOT_FILE"
echo

# Step 2: Convert to SQLite
print_step "Step 2: Converting to SQLite database..."
if cargo run --quiet -- to-sqlite "$WASOT_FILE" -d "$TEMP_DB" 2>/dev/null; then
    print_success "Conversion to SQLite completed"
else
    print_error "Failed to convert to SQLite"
    exit 1
fi
echo

# Step 3: Show database info
print_step "Step 3: Database information"
echo "----------------------------"
DB_SIZE=$(stat -c%s "$TEMP_DB" 2>/dev/null || stat -f%z "$TEMP_DB" 2>/dev/null || echo "unknown")
print_info "Database size: $DB_SIZE bytes"
echo

# Step 4: Convert back from SQLite
print_step "Step 4: Converting back to Wasot format"
echo "---------------------------------------"
if cargo run --quiet -- from-sqlite -d "$TEMP_DB" 2>/dev/null; then
    echo
    print_success "Round-trip conversion completed successfully!"
else
    print_error "Failed to convert from SQLite"
    exit 1
fi

echo
print_info "Demo completed. The output above shows the reconstructed Wasot document."