#!/bin/bash
# Plugin scaffolding — creates a new plugin directory with boilerplate.
# Usage: bash scripts/plugin-init.sh <plugin-id> [plugin-name]

set -e

PLUGIN_ID="${1:?Usage: plugin-init.sh <plugin-id> [plugin-name]}"
PLUGIN_NAME="${2:-$PLUGIN_ID}"

# Validate ID format
if ! echo "$PLUGIN_ID" | grep -qE '^[a-z0-9-]+$'; then
  echo "Error: plugin-id must be lowercase alphanumeric with hyphens only."
  exit 1
fi

# Determine target directory
CONFIG_DIR="${AGOR_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/agor}"
PLUGINS_DIR="$CONFIG_DIR/plugins"
PLUGIN_DIR="$PLUGINS_DIR/$PLUGIN_ID"

if [ -d "$PLUGIN_DIR" ]; then
  echo "Error: Plugin directory already exists: $PLUGIN_DIR"
  exit 1
fi

mkdir -p "$PLUGIN_DIR"

# Create plugin.json
cat > "$PLUGIN_DIR/plugin.json" << EOF
{
  "id": "$PLUGIN_ID",
  "name": "$PLUGIN_NAME",
  "version": "1.0.0",
  "author": "$(whoami)",
  "description": "A custom plugin for Agents Orchestrator.",
  "license": "MIT",
  "permissions": ["palette"],
  "main": "index.js"
}
EOF

# Create index.js
cat > "$PLUGIN_DIR/index.js" << 'EOF'
// Plugin entry point — runs inside a Web Worker sandbox.
// Available API (permission-gated):
//   agor.meta          — { id, name, version } (always available)
//   agor.palette       — registerCommand(name, callback)
//   agor.messages      — onMessage(callback)
//   agor.tasks         — list(), create(title), updateStatus(id, status)
//   agor.events        — emit(type, data), on(type, callback)
//   agor.notifications — send(title, body)

agor.palette.registerCommand('$PLUGIN_NAME', function() {
  agor.events.emit('notification', {
    type: 'info',
    message: 'Hello from $PLUGIN_NAME!'
  });
});
EOF

# Replace placeholder in index.js
sed -i "s/\\\$PLUGIN_NAME/$PLUGIN_NAME/g" "$PLUGIN_DIR/index.js"

echo "Plugin created at: $PLUGIN_DIR"
echo ""
echo "Files:"
echo "  $PLUGIN_DIR/plugin.json  — manifest"
echo "  $PLUGIN_DIR/index.js     — entry point"
echo ""
echo "Next steps:"
echo "  1. Edit plugin.json to set permissions"
echo "  2. Implement your plugin logic in index.js"
echo "  3. Restart Agents Orchestrator to load the plugin"
