#!/usr/bin/env bats

# Tests for manage.sh script functionality

setup() {
  # Get the directory of this test file
  TEST_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
  PROJECT_ROOT="$(cd "$TEST_DIR/../.." && pwd)"
  MANAGE_SCRIPT="$PROJECT_ROOT/tools/manage.sh"
  
  # Ensure manage.sh exists and is executable
  [ -f "$MANAGE_SCRIPT" ]
  chmod +x "$MANAGE_SCRIPT"
}

@test "manage.sh exists and is executable" {
  [ -f "$MANAGE_SCRIPT" ]
  [ -x "$MANAGE_SCRIPT" ]
}

@test "manage.sh shows help" {
  run "$MANAGE_SCRIPT" help
  [ "$status" -eq 0 ]
  echo "$output" | grep -q "Project Management Script"
  echo "$output" | grep -q "health"
  echo "$output" | grep -q "Check API health endpoint"
}

@test "manage.sh health command exists" {
  run "$MANAGE_SCRIPT" help
  [ "$status" -eq 0 ]
  echo "$output" | grep -q "health"
}

@test "manage.sh health when API not running" {
  # First stop any running services
  run "$MANAGE_SCRIPT" stop
  
  # Run health check
  run "$MANAGE_SCRIPT" health
  [ "$status" -eq 1 ]  # Should fail when API is not running
  echo "$output" | grep -q "API port 9101 not open"
  echo "$output" | grep -q "Start with:"
}

@test "manage.sh status command works" {
  run "$MANAGE_SCRIPT" status
  # Status should work regardless of running state
  [ "$status" -eq 0 ]
  echo "$output" | grep -q "ML Experiment Manager Status"
}

@test "manage.sh has all expected commands" {
  run "$MANAGE_SCRIPT" help
  [ "$status" -eq 0 ]
  
  # Check for all expected commands
  echo "$output" | grep -q "status"
  echo "$output" | grep -q "build"
  echo "$output" | grep -q "test"
  echo "$output" | grep -q "start"
  echo "$output" | grep -q "stop"
  echo "$output" | grep -q "health"
  echo "$output" | grep -q "security"
  echo "$output" | grep -q "dev"
  echo "$output" | grep -q "logs"
  echo "$output" | grep -q "cleanup"
  echo "$output" | grep -q "help"
}

@test "manage.sh health uses correct curl command" {
  # Check that the health function exists in the script
  grep -q "check_health()" "$MANAGE_SCRIPT"
  
  # Check that the curl command is present
  grep -q "curl.*X-API-Key.*password.*X-Forwarded-For.*127.0.0.1" "$MANAGE_SCRIPT"
}

@test "manage.sh health handles port check" {
  # Verify the health check uses nc for port testing
  grep -q "nc -z localhost 9101" "$MANAGE_SCRIPT"
}
