# Plugin Management API

The `ctx.majk.plugins` API provides comprehensive plugin lifecycle management, health monitoring, and administration capabilities.

## Overview

```typescript
// Access the plugin management API
const pluginAPI = ctx.majk.plugins;

// Install a plugin
await pluginAPI.install('my-plugin@1.0.0');

// Start/stop plugin lifecycle
await pluginAPI.start('my-plugin');
await pluginAPI.stop('my-plugin');

// Monitor health and logs
const health = await pluginAPI.getHealth('my-plugin');
const logs = await pluginAPI.getLogs('my-plugin');
```

## Installation Management

### install(identifier, options?)
Install a plugin from various sources.

```typescript
// Install from npm
await ctx.majk.plugins.install('my-plugin@1.0.0');

// Install from local path
await ctx.majk.plugins.install('/path/to/plugin');

// Install with options
await ctx.majk.plugins.install('my-plugin', {
  force: true,           // Force reinstall
  dev: true,            // Install as development dependency
  registry: 'custom'    // Use custom registry
});
```

**Returns:** `InstallPluginResult` with installation details and any errors.

### uninstall(pluginId)
Remove a plugin completely.

```typescript
const success = await ctx.majk.plugins.uninstall('my-plugin');
console.log(success ? 'Uninstalled' : 'Failed to uninstall');
```

**Returns:** `boolean` indicating success.

## Plugin Discovery

### list()
Get all installed plugins.

```typescript
const plugins = await ctx.majk.plugins.list();
plugins.forEach(plugin => {
  console.log(`${plugin.name} v${plugin.version} - ${plugin.status}`);
});
```

**Returns:** `PluginInfo[]` with plugin metadata and status.

### get(pluginId)
Get detailed information about a specific plugin.

```typescript
const plugin = await ctx.majk.plugins.get('my-plugin');
if (plugin) {
  console.log(`Plugin: ${plugin.name}`);
  console.log(`Status: ${plugin.status}`);
  console.log(`Capabilities: ${plugin.capabilities?.length || 0}`);
}
```

**Returns:** `PluginInfo | null` if plugin exists.

## Lifecycle Management

### start(pluginId)
Start a stopped plugin.

```typescript
await ctx.majk.plugins.start('my-plugin');
console.log('Plugin started');
```

### stop(pluginId)
Stop a running plugin gracefully.

```typescript
await ctx.majk.plugins.stop('my-plugin');
console.log('Plugin stopped');
```

### restart(pluginId)
Stop and start a plugin.

```typescript
await ctx.majk.plugins.restart('my-plugin');
console.log('Plugin restarted');
```

### reload(pluginId)
Reload plugin code without stopping (hot reload).

```typescript
await ctx.majk.plugins.reload('my-plugin');
console.log('Plugin code reloaded');
```

### enable(pluginId) / disable(pluginId)
Enable or disable a plugin.

```typescript
// Disable plugin (stops and prevents auto-start)
await ctx.majk.plugins.disable('my-plugin');

// Re-enable plugin
await ctx.majk.plugins.enable('my-plugin');
```

### isRunning(pluginId)
Check if plugin is currently running.

```typescript
if (ctx.majk.plugins.isRunning('my-plugin')) {
  console.log('Plugin is active');
} else {
  console.log('Plugin is stopped');
}
```

**Returns:** `boolean` - synchronous check.

## Health Monitoring

### getHealth(pluginId)
Get plugin health status and diagnostics.

```typescript
const health = await ctx.majk.plugins.getHealth('my-plugin');
if (health) {
  console.log(`Status: ${health.status}`);
  console.log(`Memory: ${health.memoryUsage}MB`);
  console.log(`Uptime: ${health.uptime}ms`);

  if (health.errors?.length > 0) {
    console.log('Recent errors:', health.errors);
  }
}
```

**Returns:** `PluginHealth | null` with performance metrics and error information.

### getCapabilities(pluginId)
Get plugin's registered capabilities (functions, screens, services).

```typescript
const capabilities = await ctx.majk.plugins.getCapabilities('my-plugin');
capabilities.forEach(cap => {
  console.log(`${cap.type}: ${cap.name} - ${cap.description}`);
});
```

**Returns:** `PluginCapabilityInfo[]` listing all plugin capabilities.

## Logging

### getLogs(pluginId, options?)
Retrieve plugin logs for debugging.

```typescript
// Get recent logs
const logs = await ctx.majk.plugins.getLogs('my-plugin');

// Get logs with filters
const errorLogs = await ctx.majk.plugins.getLogs('my-plugin', {
  level: 'error',        // Filter by log level
  since: Date.now() - 3600000,  // Last hour
  limit: 100            // Max entries
});

logs.forEach(log => {
  console.log(`[${log.timestamp}] ${log.level}: ${log.message}`);
});
```

**Returns:** `PluginLog[]` with timestamped log entries.

### clearLogs(pluginId)
Clear plugin's log history.

```typescript
await ctx.majk.plugins.clearLogs('my-plugin');
console.log('Logs cleared');
```

## Development Tools

### setHotReload(pluginId, enabled)
Enable/disable hot reload for development.

```typescript
// Enable hot reload for development
await ctx.majk.plugins.setHotReload('my-plugin', true);

// Disable for production
await ctx.majk.plugins.setHotReload('my-plugin', false);
```

### isHotReloadEnabled(pluginId)
Check hot reload status.

```typescript
const hotReloadEnabled = await ctx.majk.plugins.isHotReloadEnabled('my-plugin');
console.log(`Hot reload: ${hotReloadEnabled ? 'ON' : 'OFF'}`);
```

## URL Generation

### getPluginExternalUrl(pluginId, options?)
Get external URL for plugin access.

```typescript
const url = await ctx.majk.plugins.getPluginExternalUrl('my-plugin');
console.log(`Plugin accessible at: ${url}`);

// With custom options
const customUrl = await ctx.majk.plugins.getPluginExternalUrl('my-plugin', {
  path: '/api/status',
  port: 8080
});
```

**Returns:** `string` - External URL for plugin access.

### getPluginScreenUrl(pluginId, options?)
Get URL for plugin's UI screens.

```typescript
const screenUrl = await ctx.majk.plugins.getPluginScreenUrl('my-plugin');
console.log(`Plugin UI at: ${screenUrl}`);

// For specific screen
const specificScreen = await ctx.majk.plugins.getPluginScreenUrl('my-plugin', {
  screen: 'dashboard',
  params: { view: 'admin' }
});
```

**Returns:** `string` - URL for plugin UI screens.

## Common Patterns

### Plugin Health Check
```typescript
async function checkPluginHealth(pluginId: string) {
  if (!ctx.majk.plugins.isRunning(pluginId)) {
    console.log(`Plugin ${pluginId} is not running`);
    return;
  }

  const health = await ctx.majk.plugins.getHealth(pluginId);
  if (health?.status === 'unhealthy') {
    console.log(`Plugin ${pluginId} is unhealthy:`, health.errors);
    // Consider restarting
    await ctx.majk.plugins.restart(pluginId);
  }
}
```

### Plugin Lifecycle with Error Handling
```typescript
async function safePluginOperation(pluginId: string, operation: 'start' | 'stop' | 'restart') {
  try {
    await ctx.majk.plugins[operation](pluginId);
    console.log(`Plugin ${pluginId} ${operation} successful`);
  } catch (error) {
    console.error(`Failed to ${operation} plugin ${pluginId}:`, error);

    // Check logs for more details
    const logs = await ctx.majk.plugins.getLogs(pluginId, {
      level: 'error',
      limit: 5
    });
    console.log('Recent errors:', logs);
  }
}
```

### Development Workflow
```typescript
async function setupDevelopment(pluginId: string) {
  // Enable hot reload for development
  await ctx.majk.plugins.setHotReload(pluginId, true);

  // Start the plugin
  await ctx.majk.plugins.start(pluginId);

  // Get development URLs
  const externalUrl = await ctx.majk.plugins.getPluginExternalUrl(pluginId);
  const screenUrl = await ctx.majk.plugins.getPluginScreenUrl(pluginId);

  console.log('Development setup complete:');
  console.log(`- Plugin API: ${externalUrl}`);
  console.log(`- Plugin UI: ${screenUrl}`);
  console.log('- Hot reload: ENABLED');
}
```

## Type Definitions

```typescript
interface PluginInfo {
  id: string;
  name: string;
  version: string;
  status: 'running' | 'stopped' | 'error' | 'disabled';
  description?: string;
  author?: string;
  capabilities?: PluginCapabilityInfo[];
}

interface PluginHealth {
  status: 'healthy' | 'unhealthy' | 'unknown';
  uptime: number;
  memoryUsage: number;
  errors?: string[];
  lastCheck: number;
}

interface PluginLog {
  timestamp: number;
  level: 'debug' | 'info' | 'warn' | 'error';
  message: string;
  context?: any;
}

interface InstallPluginOptions {
  force?: boolean;
  dev?: boolean;
  registry?: string;
}

interface GetLogsOptions {
  level?: 'debug' | 'info' | 'warn' | 'error';
  since?: number;
  limit?: number;
}
```