#!/bin/bash
#
# Sentinel Package Manager - Package Manager Wrapper
#
# Supports: npm, yarn, pnpm, bun
#
# Usage:
#   ./sentinel.sh npm install package-name
#   ./sentinel.sh yarn add package-name
#   ./sentinel.sh pnpm add package-name
#   ./sentinel.sh bun add package-name
#

set -e

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

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
CLI_SCRIPT="$PROJECT_ROOT/bin/cli.mjs"

# Check if CLI script exists
if [ ! -f "$CLI_SCRIPT" ]; then
  # Try user-wide installation directory
  USER_INSTALL_DIR="${HOME}/.sentinel"
  if [ -f "$USER_INSTALL_DIR/bin/cli.mjs" ]; then
    CLI_SCRIPT="$USER_INSTALL_DIR/bin/cli.mjs"
    PROJECT_ROOT="$USER_INSTALL_DIR"
  else
    echo -e "${RED}❌ Error: CLI script not found${NC}" >&2
    echo -e "${YELLOW}   Expected locations:${NC}" >&2
    echo -e "${YELLOW}   - $CLI_SCRIPT${NC}" >&2
    echo -e "${YELLOW}   - $USER_INSTALL_DIR/bin/cli.mjs${NC}" >&2
    echo -e "${YELLOW}   Please run the installation script first.${NC}" >&2
    exit 1
  fi
fi

# Get package manager (first argument)
PACKAGE_MANAGER="$1"
shift

# Supported package managers
SUPPORTED_MANAGERS=("npm" "yarn" "pnpm" "bun")

if [[ ! " ${SUPPORTED_MANAGERS[@]} " =~ " ${PACKAGE_MANAGER} " ]]; then
  echo -e "${YELLOW}⚠️  Package manager '$PACKAGE_MANAGER' not explicitly supported, but proceeding...${NC}"
fi

# Get the command (add, install, i, etc.)
COMMAND="$1"
shift

# Commands that install packages
INSTALL_COMMANDS=("add" "install" "i")

# Check if this is an install command
IS_INSTALL_COMMAND=false
for cmd in "${INSTALL_COMMANDS[@]}"; do
  if [ "$COMMAND" = "$cmd" ]; then
    IS_INSTALL_COMMAND=true
    break
  fi
done

# If not an install command, just pass through
if [ "$IS_INSTALL_COMMAND" = false ]; then
  exec "$PACKAGE_MANAGER" "$COMMAND" "$@"
fi

# Preserve original arguments for actual install command
ORIGINAL_ARGS=("$@")

# Extract package names from arguments (skip flags)
PACKAGES=()
while [[ $# -gt 0 ]]; do
  case "$1" in
    # Skip common flags
    -D|--dev|--save-dev|--development)
      shift
      ;;
    -S|--save|--save-prod|--production)
      shift
      ;;
    -O|--save-optional|--optional)
      shift
      ;;
    -P|--save-peer|--peer)
      shift
      ;;
    -E|--save-exact|--exact)
      shift
      ;;
    -W|--workspace|--workspace-root)
      shift
      ;;
    -g|--global)
      shift
      ;;
    --*|-*)
      # Skip other flags
      shift
      ;;
    *)
      # This is a package name
      PACKAGES+=("$1")
      shift
      ;;
  esac
done

# If no packages specified, just run the install (installs from package.json)
if [ ${#PACKAGES[@]} -eq 0 ]; then
  echo -e "${BLUE}📦 Installing dependencies from package.json...${NC}"
  exec "$PACKAGE_MANAGER" "$COMMAND" "$@"
fi

# Validate packages before installation
echo -e "${BLUE}🔍 Validating packages against security blacklist...${NC}"

ALL_VALID=true
BLOCKED_PACKAGES=()

for PACKAGE in "${PACKAGES[@]}"; do
  # Run validation script using CLI (quiet mode to avoid duplicate output)
  if ! node "$CLI_SCRIPT" scan "$PACKAGE" --logMode=quiet 2>&1; then
    ALL_VALID=false
    BLOCKED_PACKAGES+=("$PACKAGE")
  fi
done

# If any package is blocked, don't proceed
if [ "$ALL_VALID" = false ]; then
  echo ""
  echo -e "${RED}${BOLD}╔════════════════════════════════════════════════════════════════╗${NC}"
  echo -e "${RED}${BOLD}║                    INSTALLATION BLOCKED                       ║${NC}"
  echo -e "${RED}${BOLD}╚════════════════════════════════════════════════════════════════╝${NC}"
  echo ""
  echo -e "${RED}❌ The following package(s) are compromised and cannot be installed:${NC}"
  for PACKAGE in "${BLOCKED_PACKAGES[@]}"; do
    echo -e "${RED}   • $PACKAGE${NC}"
  done
  echo ""
  echo -e "${YELLOW}⚠️  Security Policy: Compromised packages are blocked to prevent${NC}"
  echo -e "${YELLOW}   security vulnerabilities and supply chain attacks.${NC}"
  echo ""
  echo -e "${YELLOW}💡 Alternatives:${NC}"
  echo -e "${YELLOW}   • Use a different version of the package${NC}"
  echo -e "${YELLOW}   • Find an alternative package${NC}"
  echo -e "${YELLOW}   • Contact the security team for exceptions${NC}"
  echo ""
  exit 1
fi

# All packages are valid, proceed with installation
echo -e "${GREEN}✅ All packages validated successfully${NC}"
echo -e "${BLUE}📦 Proceeding with installation...${NC}"
echo ""

# Run the actual package manager command with original arguments
exec "$PACKAGE_MANAGER" "$COMMAND" "${ORIGINAL_ARGS[@]}"

