#!/bin/bash
set -e

# Quality Rails Installation Script
# Usage: ./install.sh --template typescript-node [--target /path/to/project]

TEMPLATE=""
TARGET_DIR="."

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --template)
      TEMPLATE="$2"
      shift 2
      ;;
    --target)
      TARGET_DIR="$2"
      shift 2
      ;;
    *)
      echo "Unknown option: $1"
      echo "Usage: $0 --template <template-name> [--target <directory>]"
      exit 1
      ;;
  esac
done

if [ -z "$TEMPLATE" ]; then
  echo "Error: --template is required"
  echo "Available templates: typescript-node, typescript-nextjs, python, monorepo"
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
TEMPLATE_DIR="$REPO_ROOT/templates/$TEMPLATE"

if [ ! -d "$TEMPLATE_DIR" ]; then
  echo "Error: Template '$TEMPLATE' not found at $TEMPLATE_DIR"
  exit 1
fi

echo "Installing Quality Rails: $TEMPLATE"
echo "Target directory: $TARGET_DIR"
echo ""

# Copy template files
echo "Copying template files..."
cp -r "$TEMPLATE_DIR/.husky" "$TARGET_DIR/" 2>/dev/null || true
cp "$TEMPLATE_DIR/.lintstagedrc.js" "$TARGET_DIR/" 2>/dev/null || true
cp "$TEMPLATE_DIR/.eslintrc.strict.js" "$TARGET_DIR/.eslintrc.js" 2>/dev/null || true
cp "$TEMPLATE_DIR/tsconfig.strict.json" "$TARGET_DIR/tsconfig.json" 2>/dev/null || true
cp "$TEMPLATE_DIR/.woodpecker.yml" "$TARGET_DIR/" 2>/dev/null || true

# Copy shared gitleaks config from templates root
SHARED_TEMPLATES="$(dirname "$TEMPLATE_DIR")"
cp "$SHARED_TEMPLATES/.gitleaks.toml" "$TARGET_DIR/" 2>/dev/null || true

echo "✓ Files copied"

# Check if package.json exists
if [ -f "$TARGET_DIR/package.json" ]; then
  echo ""
  echo "⚠ package.json exists. Please manually merge dependencies from:"
  echo "  $TEMPLATE_DIR/package.json.snippet"
else
  echo "⚠ No package.json found. Create one and add dependencies from:"
  echo "  $TEMPLATE_DIR/package.json.snippet"
fi

echo ""
echo "✓ Quality Rails installed successfully!"
echo ""
echo "Next steps:"
echo "1. Install dependencies: npm install"
echo "2. Initialize husky: npx husky install"
echo "3. Install gitleaks: https://github.com/gitleaks/gitleaks#installing"
echo "4. Run verification: ~/.config/mosaic/bin/mosaic-quality-verify --target $TARGET_DIR"
echo "5. (Optional) Scan full history: gitleaks git --redact --verbose"
echo ""
