#!/bin/bash
# Shared library for shell test scripts
# Source this file: source ./test_lib.sh

set -euo pipefail

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

# Test counters
TESTS_RUN=0
TESTS_PASSED=0
TESTS_FAILED=0

# Project paths
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
PRODUCTION_DB="$PROJECT_DIR/db/skraak.duckdb"
DEFAULT_TEST_DB="$PROJECT_DIR/db/test.duckdb"

# Check that skraak binary exists
check_binary() {
    if [ ! -f "$PROJECT_DIR/skraak" ]; then
        echo -e "${RED}Error: skraak binary not found. Run 'go build' first.${NC}"
        exit 1
    fi
}

# Create fresh test database from production
# Returns path to fresh test DB (in /tmp)
fresh_test_db() {
    if [ ! -f "$PRODUCTION_DB" ]; then
        echo -e "${RED}Error: Production database not found at $PRODUCTION_DB${NC}"
        exit 1
    fi

    local test_db="/tmp/skraak_test_$$.duckdb"
    cp "$PRODUCTION_DB" "$test_db"
    echo "$test_db"
}

# Cleanup test database
cleanup_test_db() {
    local db_path="$1"
    if [ -n "$db_path" ] && [ -f "$db_path" ]; then
        rm -f "$db_path"
        # Also remove DuckDB temp files
        rm -f "${db_path}.wal" "${db_path}.tmp" 2>/dev/null || true
    fi
}

# Generate a minimal valid WAV file (1-channel, 16-bit PCM, silence)
# Usage: generate_wav <output_path> [duration_seconds] [sample_rate]
# Default: 1 second, 16000 Hz sample rate
# Requires: python3
generate_wav() {
    local output_path="$1"
    local duration_sec="${2:-1}"
    local sample_rate="${3:-16000}"

    python3 -c "
import struct, sys
sr=$sample_rate; dur=$duration_sec; n=sr*dur; ds=n*2; fs=36+ds
with open('$output_path','wb') as f:
    f.write(b'RIFF')
    f.write(struct.pack('<I', fs))
    f.write(b'WAVE')
    f.write(b'fmt ')
    f.write(struct.pack('<IHHIIHH', 16, 1, 1, sr, sr*2, 2, 16))
    f.write(b'data')
    f.write(struct.pack('<I', ds))
    f.write(b'\x00' * ds)
"
}

# Print test summary
print_summary() {
    echo ""
    echo "=== Summary ==="
    echo -e "Tests run: $TESTS_RUN"
    echo -e "Passed: ${GREEN}$TESTS_PASSED${NC}"
    if [ "$TESTS_FAILED" -gt 0 ]; then
        echo -e "Failed: ${RED}$TESTS_FAILED${NC}"
    else
        echo -e "Failed: $TESTS_FAILED"
    fi

    if [ "$TESTS_FAILED" -gt 0 ]; then
        return 1
    fi
    return 0
}