# 🎨 Interactive TUI Guide

## Overview

The Cognitive Guard TUI (Terminal User Interface) is a full-featured interactive application that helps you add documentation to complex functions directly from your terminal.

## Launching the TUI

```bash
cognitive-guard tui
```

The TUI will automatically:
1. Scan your codebase for violations
2. Report how many violations were found
3. Launch the interactive interface (if violations exist)

## Features

### 📊 Real-time Statistics
- Total violations count
- Number of violations fixed  
- Remaining violations
- Current progress (e.g., "2/5")
- Target coverage percentage

### 🚫 Violation Details
For each violation, you see:
- **File name** and full path
- **Function name**
- **Line number** where the function starts
- **Brain Score** (cognitive complexity)
- **Severity level** (simple/moderate/complex/very_complex)
- **Emoji indicator** (🟢🟡🟠🔴)

### 📝 Code Preview
- Shows the actual function code (first 10 lines)
- Helps you understand what the function does
- Makes it easy to write accurate documentation

### ✍️ Interactive Editor
- Pre-filled with a docstring template
- Includes placeholders for:
  - Function description
  - Arguments (Args)
  - Return value (Returns)
  - Special notes about complexity
- Full text editing with Python syntax highlighting
- Template reminds you of the complexity score

### 💾 Save Functionality
The TUI can actually save docstrings to your files:
- Reads the original file
- Detects proper indentation
- Inserts the docstring right after the function definition
- Preserves all other code exactly as-is
- Shows confirmation message when saved

### 🎮 Navigation

#### Button Controls
- **💾 Save & Next** - Saves current docstring and moves to next violation
- **⏭️  Skip** - Skip current violation without saving
- **⬅️  Previous** - Go back to previous violation
- **❌ Exit** - Quit the TUI

#### Keyboard Shortcuts
- **Ctrl+S** - Save current docstring
- **Ctrl+N** - Next violation
- **Ctrl+P** - Previous violation
- **Q** - Quit the application

### 📈 Progress Tracking
- Shows how many violations you've fixed in real-time
- Updates statistics after each save
- Displays "All violations reviewed!" when complete

## Workflow Example

1. Launch TUI: `cognitive-guard tui`

2. See first violation:
   ```
   🚫 Violation 1/2
   📁 File: sample_code.py
   🔧 Function: complex_undocumented
   🧠 Brain Score: 15 🟠
   ⚠️  Severity: COMPLEX
   ```

3. View code preview to understand the function

4. Edit the docstring template in the editor:
   ```python
   """
   Calculate sum based on conditional logic
   
   Args:
       a: First number
       b: Second number
       c: Third number
   
   Returns:
       int: Calculated sum based on conditions
   
   Note:
       This function has a complexity score of 15.
       Consider refactoring if possible.
   """
   ```

5. Press **Ctrl+S** or click **💾 Save & Next**

6. See confirmation: "✅ Saved docstring to sample_code.py! Fixed: 1/2"

7. Move to next violation automatically

8. Repeat until all violations are fixed

9. See completion message:
   ```
   🎉 All violations reviewed!
   • Fixed: 2
   • Skipped: 0
   Press 'q' to quit.
   ```

## How Saving Works

When you save a docstring:

1. **File Reading**: TUI reads the entire file
2. **Location Detection**: Finds the function at the specified line number
3. **Indentation Detection**: Matches the function's indentation level
4. **Docstring Insertion**: Inserts docstring right after function signature
   - Adds 4 spaces more than function indentation (PEP 257)
   - Preserves all blank lines and formatting
5. **File Writing**: Writes the modified content back
6. **Verification**: Shows success/error message

### Before:
```python
def complex_function(a, b, c):
    result = 0
    if a > 0:
        # ...
```

### After:
```python
def complex_function(a, b, c):
    """
    Description here
    
    Args:
        a: First parameter
        b: Second parameter  
        c: Third parameter
    
    Returns:
        Result value
    """
    result = 0
    if a > 0:
        # ...
```

## Validation

The TUI validates your docstrings before saving:

- ✅ **Required**: Non-empty docstring
- ✅ **Required**: Must remove "FIXME" placeholder
- ❌ **Warning**: Shows error if validation fails
- 💡 **Tip**: Write a proper description before saving

## Status Messages

The TUI shows helpful status messages:

- ✅ "Saved docstring to file.py! Fixed: 1/5"
- ⚠️  "Please write a proper docstring (remove FIXME)"
- ⚠️  "Already at first violation"
- ✅ "All violations reviewed! Press 'q' to quit"
- ❌ "Error saving: [error details]"

Messages auto-clear after 3 seconds.

## Tips & Best Practices

### Writing Good Docstrings

1. **Be specific**: Describe what the function actually does
2. **Document parameters**: Explain each argument's purpose and type
3. **Explain the return**: What does the function return?
4. **Add context**: Why is this function complex? Any gotchas?
5. **Follow PEP 257**: Use triple quotes, proper formatting

### Handling High Complexity

If you see a very high Brain Score (16+):

1. **Document it well** - The TUI makes this easy
2. **Consider refactoring** - Break into smaller functions
3. **Add extra notes** - Explain the complexity in the docstring
4. **Update later** - The TUI lets you iterate

### Efficient Workflow

1. **Use keyboard shortcuts** - Much faster than clicking
2. **Skip simple cases** - Focus on the truly complex ones first
3. **Review code preview** - Understand before documenting
4. **Save frequently** - Don't lose your work
5. **Batch process** - Fix all violations in one session

## Troubleshooting

### "No violations found"
✅ Great! All your complex functions are documented.

### TUI won't launch
❌ Make sure you run `cognitive-guard init` first
❌ Check that you're in a directory with a `.cognitive-guard.yml`

### Save fails
❌ File permissions - ensure the file is writable
❌ Syntax error - check your docstring formatting
❌ File moved - make sure the file still exists

### Editor feels slow
💡 The TUI updates smoothly on most terminals
💡 Try a different terminal emulator if needed

## Advanced Usage

### Integration with Git
After using the TUI to fix violations:

```bash
git add .
git commit -m "docs: add docstrings to complex functions"
```

The pre-commit hook will now pass!

### Automation
You can script the TUI workflow:

```bash
# Scan and show violations
cognitive-guard scan

# Launch TUI to fix them
cognitive-guard tui

# Verify all fixed
cognitive-guard scan
```

### Configuration
Adjust complexity threshold in `.cognitive-guard.yml`:

```yaml
complexity_threshold: 15  # Only require docs for score > 15
```

Then the TUI will show fewer violations.

## Comparison: CLI vs TUI

| Feature | `scan` command | `tui` command |
|---------|----------------|---------------|
| Find violations | ✅ | ✅ |
| Show statistics | ✅ | ✅ |
| Interactive fixing | ❌ | ✅ |
| Code preview | ❌ | ✅ |
| Docstring templates | ❌ | ✅ |
| Save to files | ❌ | ✅ |
| Navigation | ❌ | ✅ |
| Real-time progress | ❌ | ✅ |

**Use `scan`** for quick checks, CI/CD, reporting.  
**Use `tui`** for actually fixing violations interactively.

## Summary

The Cognitive Guard TUI is a powerful tool that:
- 🔍 **Finds** complex undocumented functions
- 📝 **Guides** you through writing docstrings
- 💾 **Saves** directly to your files
- 📊 **Tracks** your progress in real-time
- 🎮 **Makes** documentation fun and interactive

Launch it with: `cognitive-guard tui`

Happy documenting! 🚀
