#!/bin/bash
set -e

echo "▶ Building render_regex..."
cargo build -p render_regex

OUTDIR="output/cli_tests"
rm -rf "$OUTDIR"
mkdir -p "$OUTDIR"

# Helper: assert file exists and is non-empty
assert_file_exists() {
    if [ ! -s "$1" ]; then
        echo "❌ Missing or empty: $1"
        exit 1
    else
        echo "✅ Found: $1"
    fi
}

# Test 1: All stages with default layout and slug
echo "[1] all stages with slug"
cargo run -p render_regex -- 'a(b|c)*d' --slug test1 --quiet --output-dir "$OUTDIR/test1"
for stage in ast nfa dfa; do
    assert_file_exists "$OUTDIR/test1/test1_${stage}.svg"
done

# Test 2: AST with tree layout and custom output file
echo "[2] AST with custom output name"
cargo run -p render_regex -- 'xyz' --stage ast --layout tree --output-dir "$OUTDIR/test2" --output test_ast.svg --quiet
assert_file_exists "$OUTDIR/test2/test_ast.svg"

# Test 3: DFA with nested output path
echo "[3] DFA to subfolder"
mkdir -p "$OUTDIR/test3/nested"
cargo run -p render_regex -- 'def' --stage dfa --output "$OUTDIR/test3/nested/dfa_custom.svg" --quiet
assert_file_exists "$OUTDIR/test3/nested/dfa_custom.svg"

# Test 4: Custom slug to nested output-dir
echo "[4] Custom slug to target dir"
cargo run -p render_regex -- 'abc*' --slug weird_slug --output-dir "$OUTDIR/test4" --quiet
assert_file_exists "$OUTDIR/test4/weird_slug_ast.svg"

# Test 5: Print output path explicitly
echo "[5] Print-paths mode"
cargo run -p render_regex -- 'hello|world' --stage dfa --print-paths --output-dir "$OUTDIR/test5"

echo "🧼 Cleaning up test outputs..."
rm -rf "$OUTDIR"

echo "✅ All CLI integration tests passed."
