# Setup Wizard Plugin Specification

## Overview

The Setup Wizard Plugin provides an interactive first-time user onboarding experience. It guides new users through initial configuration of LLM connection, keyboard shortcuts reference, and slash commands reference.

**Location:** `plugins/fullscreen/setup_wizard_plugin.py`

**Version:** 1.0.0

## Features

### Interactive Configuration

- **Single-screen form**: All configuration fields on one screen
- **Form navigation**: Tab/Arrow keys to navigate between fields
- **Input validation**: Real-time validation of configuration values
- **Tool format selection**: Dropdown for OpenAI/Anthropic formats
- **Profile management**: Creates named profiles for easy switching

### Onboarding Content

- **Kollabor ASCII banner**: Visual branding
- **Keyboard shortcuts**: Reference of key bindings
- **Slash commands**: Reference of available commands
- **Configuration help**: Inline help for each field
- **Tips and hints**: Contextual guidance for new users

### Full-Screen Integration

Built on the full-screen plugin framework:
- **Modal overlay**: Full-screen modal wizard
- **Animation support**: Fade and bounce animations
- **Responsive layout**: Adapts to terminal size
- **Keyboard-driven**: No mouse required

## Architecture

### Plugin Structure

```python
class SetupWizardPlugin(FullScreenPlugin):
    - initialize(renderer) -> bool
    - on_start() -> None
    - render_frame(delta_time: float) -> bool
    - handle_key(key_press: KeyPress) -> None
    - on_end() -> None
    - set_managers(config, profile_manager) -> None
    - _render_form() -> None
    - _render_banner() -> None
    - _render_tips() -> None
    - _handle_form_input(key_press: KeyPress) -> None
    - _save_profile() -> None
```

### Form Fields

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `profile_name` | text | `"local"` | Profile name for saving configuration |
| `api_url` | text | `"http://localhost:1234"` | LLM API endpoint |
| `model` | text | `"qwen3-4b"` | Model name to use |
| `token` | text | `""` | API token (optional, can use env var) |
| `temperature` | text | `"0.7"` | Temperature setting |
| `tool_format` | dropdown | `"openai"` | Tool format (openai/anthropic) |

### Kollabor Banner

ASCII art banner displayed at top of wizard:

```
╭──────────────────────────────────────────────────╮
│ ▄█─●─●─█▄  █ ▄▀ █▀▀█ █   █   █▀▀█ █▀▀▄ █▀▀█ █▀▀█ │
│ ●──███──●  █▀▄  █  █ █   █   █▄▄█ █▀▀▄ █  █ █▄▄▀ │
│ ▀█─●─●─█▀  █  █ █▄▄█ █▄▄ █▄▄ █  █ █▄▄▀ █▄▄█ █ █▄ │
╰──────────────────────────────────────────────────╯
```

## Configuration

### Configuration Options

The setup wizard creates configuration for the main LLM service:

| Option | Description |
|--------|-------------|
| `profile_name` | Name of the profile to create |
| `llm.api_url` | API endpoint for LLM requests |
| `llm.model` | Model name to use |
| `llm.token` | API authentication token |
| `llm.temperature` | Temperature for generation (0.0-2.0) |
| `llm.tool_format` | Tool format (openai/anthropic) |

### Generated Configuration

After completion, wizard saves to `~/.kollabor-cli/config.json`:

```json
{
  "profiles": {
    "local": {
      "api_url": "http://localhost:1234",
      "model": "qwen3-4b",
      "token": "",
      "temperature": 0.7,
      "tool_format": "openai"
    }
  },
  "active_profile": "local"
}
```

## User Interface

### Form Layout

```
╭──────────────────────────────────────────────────╮
│ ▄█─●─●─█▄  █ ▄▀ █▀▀█ █   █   █▀▀█ █▀▀▄ █▀▀█ █▀▀█ │
│ ●──███──●  █▀▄  █  █ █   █   █▄▄█ █▀▀▄ █  █ █▄▄▀ │
│ ▀█─●─●─█▀  █  █ █▄▄█ █▄▄ █▄▄ █  █ █▄▄▀ █▄▄█ █ █▄ │
╰──────────────────────────────────────────────────╯

Setup Wizard
════════════════════════════════════════════════

Profile Name: [local_________________]

API URL:       [http://localhost:1234___]

Model:        [qwen3-4b_____________]

Token:        [_____________________]

Temperature:  [0.7_________________]

Tool Format:   [openai ▼] (Tab to switch)

────────────────────────────────────────────────────
Tips: Use Tab to navigate, Enter to save, Esc to cancel

Key Shortcuts:   Slash Commands:
  Tab - Next field   /help - Show help
  Enter - Save       /config - Edit config
  Esc - Cancel       /status - Show status
  ↑/↓ - Navigate    /save - Save conversation
```

### Tips Section

Contextual tips displayed below form:
- Form navigation instructions
- Keyboard shortcuts reference
- Slash commands reference
- Help for current field

## Keyboard Controls

### Navigation

| Key | Action |
|-----|--------|
| `Tab` | Move to next field |
| `Shift+Tab` | Move to previous field |
| `↑/↓` | Navigate between fields |
| `Home` | Move to start of field |
| `End` | Move to end of field |

### Editing

| Key | Action |
|-----|--------|
| `Backspace` | Delete character before cursor |
| `Delete` | Delete character at cursor |
| `←/→` | Move cursor left/right |
| Character keys | Type character |

### Actions

| Key | Action |
|-----|--------|
| `Enter` | Save configuration and exit |
| `Esc` | Cancel and exit without saving |
| `F1` | Show help for current field |

### Tool Format Selection

When on "Tool Format" field:
- `Tab` or `→` or `→` - Switch to next format
- `Shift+Tab` or `←` - Switch to previous format

Available formats:
- `openai` - OpenAI tool format
- `anthropic` - Anthropic tool format

## Implementation Details

### State Management

```python
# Form state
self.fields = [
    "profile_name", "api_url", "model", 
    "token", "temperature", "tool_format"
]
self.current_field_index = 0
self.field_values = {field: default for field in fields}
self.cursor_positions = {field: len(default) for field in fields}

# Page state: 0 = form, 1 = tips (if terminal too small)
self.current_page = 0

# Completion flags
self.completed = False
self.skipped = False
```

### Animation Framework

```python
self.animation_framework = AnimationFramework()
self.demo_animations = {
    'title_fade': animation_framework.fade_in(1.5, start_time),
    'bounce': animation_framework.bounce_in(1.0, start_time + 0.3)
}
```

### Manager Injection

```python
def set_managers(self, config, profile_manager):
    """Set config and profile manager for saving."""
    self._config = config
    self._profile_manager = profile_manager
```

### Profile Saving

```python
def _save_profile(self):
    """Save configuration as new profile."""
    profile = {
        "api_url": self.field_values["api_url"],
        "model": self.field_values["model"],
        "token": self.field_values["token"],
        "temperature": float(self.field_values["temperature"]),
        "tool_format": self.field_values["tool_format"]
    }
    
    profile_name = self.field_values["profile_name"]
    self._profile_manager.save_profile(profile_name, profile)
    self._profile_manager.set_active(profile_name)
```

## Display Optimization

### Render State Caching

```python
# Only redraw when state actually changes
current_state = self._get_render_state()
if current_state != self._last_render_state:
    self._render_full()
    self._last_render_state = current_state
```

### Reduced FPS

```python
# Lower FPS for static form (reduces CPU)
self.target_fps = 3.0
```

### Page Switching

If terminal height is too small for full form + tips:
- Page 0: Form only
- Page 1: Tips and shortcuts
- User can toggle with `F2` key

## Error Handling

### Common Errors

| Error | Cause | Resolution |
|-------|-------|------------|
| Invalid URL | API URL is malformed | Check URL format, include http:// or https:// |
| Invalid temperature | Not a valid number | Enter number between 0.0 and 2.0 |
| Profile exists | Profile name already in use | Choose different name or overwrite |
| Save failed | Cannot write config file | Check file permissions |

### Validation

Real-time validation for each field:
- `api_url`: Must be valid URL format
- `temperature`: Must be valid float, 0.0-2.0 range
- `tool_format`: Must be one of available formats
- `profile_name`: Cannot be empty

## Usage Flow

### Starting the Wizard

1. New installation detects no configuration
2. User launches `kollab`
3. Setup wizard automatically opens
4. User fills in configuration
5. User presses Enter to save
6. Profile created and set as active
7. Wizard exits, main app starts

### Manual Launch

User can manually launch wizard:

```bash
# Via command-line flag
kollab --setup

# Via slash command (if implemented)
/setup

# Via config menu
/config -> Setup Wizard
```

## Implementation Checklist

### Core Functionality
- [x] Interactive form with all fields
- [x] Keyboard navigation
- [x] Input validation
- [x] Profile saving
- [x] ASCII banner display
- [x] Tips and shortcuts reference

### Full-Screen Framework
- [x] Animation support
- [x] Keyboard handling
- [x] Responsive layout
- [x] Render state optimization

### Configuration
- [x] Profile management integration
- [x] Config manager injection
- [x] Active profile setting

### Error Handling
- [x] Input validation
- [x] Profile conflict detection
- [x] Save failure handling

## Best Practices

### First-Time User Experience

- **Minimal defaults**: Sensible defaults that work out-of-the-box
- **Clear guidance**: Inline help and tips
- **Fast completion**: Single screen, no multi-page wizard
- **No barriers**: User can skip or cancel at any time

### Configuration Design

- **Profile-based**: Encourages multiple configurations
- **Explicit naming**: Users name their own profiles
- **Validated input**: Prevents invalid configurations
- **Clear feedback**: Shows what's being saved

## Related Documentation

- /docs/reference/fullscreen-framework.md - Full-screen plugin framework
- /docs/configuration/profiles.md - Profile management
- /docs/user-guide/first-time-setup.md - First-time setup guide

## Future Enhancements

### Planned Features

- [ ] Profile presets (OpenAI, Anthropic, Local)
- [ ] Connection test wizard
- [ ] Model auto-discovery
- [ ] Advanced configuration (custom headers, timeouts)
- [ ] Import/export profiles
- [ ] Profile cloning

### UX Improvements

- [ ] Field help tooltips
- [ ] Validation error highlighting
- [ ] Auto-fill from environment variables
- [ ] Configuration preview before saving
- [ ] Undo/redo support

## Troubleshooting

### Wizard Won't Start

1. Check if wizard is enabled
2. Verify full-screen framework is available
3. Check for existing configuration (may auto-skip)
4. Review logs for initialization errors

### Can't Save Profile

1. Check write permissions for config directory
2. Verify profile name is not empty
3. Check profile manager is properly initialized
4. Review logs for save errors

### Form Unresponsive

1. Verify keyboard event handling
2. Check full-screen renderer is active
3. Confirm terminal size is adequate
4. Try resizing terminal

## Extension Points

### Adding New Fields

To add a new configuration field:

1. Add field to `self.fields` list
2. Add default value to `self.field_values`
3. Add cursor position to `self.cursor_positions`
4. Add field rendering in `_render_form()`
5. Add field handling in `_handle_form_input()`
6. Add field to profile save in `_save_profile()`

### Custom Validation

Add custom validation for fields:

```python
def _validate_field(self, field_name: str, value: str) -> bool:
    if field_name == "api_url":
        return self._is_valid_url(value)
    elif field_name == "temperature":
        try:
            temp = float(value)
            return 0.0 <= temp <= 2.0
        except ValueError:
            return False
    return True
```

### Custom Animations

Add custom animations:

```python
self.demo_animations = {
    'custom_effect': animation_framework.custom_effect(
        duration=2.0,
        start_time=current_time,
        params={...}
    )
}
```
