#!/bin/bash

# Agent 5: Module Tester
# Tests that a module works correctly after migration
# Usage: ./05_test_module.sh module_name

if [ $# -eq 0 ]; then
    echo "Usage: $0 <module_name>"
    echo "Example: $0 servers"
    echo "Example: $0 utils"
    exit 1
fi

MODULE="$1"

case $MODULE in
    "servers")
        MODULE_PATH="core/nulib/servers"
        TEST_COMMANDS=("./core/nulib/provisioning server help" "nu --ide-check core/nulib/servers/*.nu")
        ;;
    "utils")
        MODULE_PATH="core/nulib/lib_provisioning/utils"
        TEST_COMMANDS=("nu --ide-check core/nulib/lib_provisioning/utils/*.nu")
        ;;
    "taskservs")
        MODULE_PATH="core/nulib/taskservs"
        TEST_COMMANDS=("./core/nulib/provisioning taskserv help" "nu --ide-check core/nulib/taskservs/*.nu")
        ;;
    "main")
        MODULE_PATH="core/nulib/main_provisioning"
        TEST_COMMANDS=("./core/nulib/provisioning help" "nu --ide-check core/nulib/main_provisioning/*.nu")
        ;;
    *)
        echo "❌ Unknown module: $MODULE"
        echo "Available modules: servers, utils, taskservs, main"
        exit 1
        ;;
esac

echo "🧪 Launching Module Tester Agent for: $MODULE"

# Create knowledge bundle for agent
KNOWLEDGE=$(cat << 'EOF'
# Module Testing Task

## Test Levels:
1. **Syntax**: nu --ide-check for all .nu files
2. **Import**: Check all imports resolve correctly
3. **Function**: Test key functions return expected types
4. **Integration**: Test module works with rest of system

## Success Criteria:
- All syntax validation passes
- No import errors
- Key functions return expected values
- No runtime errors in basic operations

## Report Format:
```json
{
  "module": "servers",
  "syntax_passed": true,
  "imports_passed": true,
  "functions_tested": 8,
  "functions_passed": 8,
  "integration_passed": true,
  "errors": []
}
```
EOF
)

# Launch Claude Code agent
claude-code task \
  --description "Test $MODULE module after migration" \
  --prompt "$KNOWLEDGE

TARGET MODULE: $MODULE
MODULE PATH: $MODULE_PATH
TASK: Comprehensive testing of module functionality
TESTS TO RUN:
$(printf '%s\n' "${TEST_COMMANDS[@]}")

OUTPUT: JSON test report with pass/fail status and any errors found" \
  --type "general-purpose" \
  > ".migration/state/test_${MODULE}.json"

# Check if tests passed
if [ -f ".migration/state/test_${MODULE}.json" ]; then
    echo "✅ Module testing complete for $MODULE"
    echo "📊 Results in .migration/state/test_${MODULE}.json"

    # Update migration state
    echo "$(date): Tested module $MODULE" >> .migration/state/tests_completed.log
else
    echo "❌ Module testing failed for $MODULE"
fi